PHP File Upload

PHP allows you to upload files to the server using the $_FILES superglobal. This is useful for allowing users to submit files through a web form.

HTML Form for File Upload

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select file to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload File" name="submit">
</form>

Explanation: This HTML form allows users to select a file to upload. The enctype="multipart/form-data" attribute is necessary for file uploads.

PHP Script to Handle File Upload

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file " . htmlspecialchars(basename($_FILES["fileToUpload"]["name"])) . " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

Explanation: This PHP script checks if the form was submitted, then moves the uploaded file to the specified directory. The move_uploaded_file() function is used to handle the file upload securely.