PHP File Upload

PHP File Upload is a feature that allows users to upload files from their computer to a server using a web browser. Here are some examples of how to use PHP’s file upload functionality:

  1. Creating an 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>
  1. Processing the uploaded file in PHP:
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
if (isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}

In the first example, an HTML form is created with a file input field that allows users to select a file to upload. The form’s enctype attribute is set to multipart/form-data, which is required for file uploads.

In the second example, the file upload is processed in PHP. The uploaded file is first checked to see if it is an image. If it is, the file is moved from its temporary location on the server to the specified upload directory. If the file upload is successful, a success message is displayed. If there is an error uploading the file, an error message is displayed.

It’s important to ensure that your code is secure and that users cannot upload or write files maliciously. In addition, it’s a good practice to check the file type and size, and to sanitize the filename to prevent security issues. These are just a few examples of PHP’s file upload functionality. By using these functions, developers can create more dynamic and powerful web applications that allow users to upload and manage files on the server.