PHP file upload code


Answers ( 1 )


    I'll provide an answer with a detailed text description and a code example.

    In PHP, uploading a file involves handling an HTML form with an input type of file and processing this file on the server using PHP. Below is a basic example of how to implement file uploading in PHP:

    HTML Form for File Upload

    First, you need an HTML form that allows users to select a file to upload. This form should use the POST method and must include enctype="multipart/form-data" to correctly transmit the file.

    <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">

    PHP Script to Handle the Upload (upload.php)

    Now, you need a PHP script to process the uploaded file. This script checks for errors, validates the file, and moves it to a directory on your server.

    $target_dir = "uploads/"; // Directory where files will be uploaded
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    // Check file size (example: limit to 5MB)
    if ($_FILES["fileToUpload"]["size"] > 5000000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    // Allow certain file formats (example: jpg, png, jpeg, gif)
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    } else {
        // Attempt to upload the file
        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.";

    Important Notes

    1. Security Concerns: Always validate and sanitize file inputs. This example does not include comprehensive security measures.
    2. Server Configuration: Ensure your server is configured to handle file uploads (e.g., adequate file size limits in php.ini).
    3. Directory Permissions: The directory where files are being uploaded should have the appropriate write permissions.

    This code provides a basic framework for uploading files using PHP. Remember to tailor it to your specific needs and to implement robust security measures as required.

Leave an answer