PHP File Upload

PHP allows us to upload files to the server in the conjugation with HTML. You can upload any kind of files like images, pdf, Microsoft word documents, zip file, executable file, or any other file.

You can upload files to the server using the below steps.

#Step 1: Creating an HTML form to upload file

The following example creates a simple HTML form to upload the file.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>File Upload Form</title>
</head>
<body>
    <form action="uploader.php" method="post" enctype="multipart/form-data">
        <h2>Upload a File</h2>
        <label for="fileSelect">Filename:</label>
        <input type="file" name="photo" id="fileSelect">
        <input type="submit" name="submit" value="Upload">
        <p><strong>Note:</strong> Only .jpg, .jpeg, .gif, .png formats allowed to a max size of 2 MB.</p>
    </form>
</body>
</html>

You can notice that we have used “fileselect” attribute for browsing the file from the local computer. The upload form must use HTTP post and enctype=”multipart/form-data”. This attribute ensures that the form data is encoded as multipart MIME data – which is required for uploading the large quantities of binary files such as images, audios, and videos.

#Step 2: Processing the uploaded file

Below is the script of the uploader.php which will process the uploaded file. The file will be uploaded to a specific location on a permanent basis and some security check will be done like file type and file size check to ensure the correct file type and file size is within the limit.

<?php
// Check if the form was submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
    // Check if file was uploaded without errors
    if(isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0){
        $allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
        $filename = $_FILES["photo"]["name"];
        $filetype = $_FILES["photo"]["type"];
        $filesize = $_FILES["photo"]["size"];
    
        // Verify file extension
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");
    
        // Verify file size - 5MB maximum
        $maxsize = 2 * 1024 * 1024;
        if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");
    
        // Verify MYME type of the file
        if(in_array($filetype, $allowed)){
            // Check whether file exists before uploading it
            if(file_exists("upload\" . $filename)){
                echo $filename ;
            } else{
                move_uploaded_file($_FILES["photo"]["tmp_name"], "upload\" . $filename);
                echo "Your file was uploaded successfully.";
            } 
        } else{
            echo "Error: There was a problem uploading your file. Please try again."; 
        }
    } else{
        echo "Error: " . $_FILES["photo"]["error"];
    }
}
?>

HERE,

Once the form is submitted after uploading the file, the uploaded files can be accessed by $_FILES array.

  • $_FILES[“photo”][“name”] — This array value specifies the original name of the file, including the file extension. It doesn’t include the file path.
  • $_FILES[“photo”][“type”] — This array value specifies the MIME type of the file.
  • $_FILES[“photo”][“size”] — This array value specifies the file size, in bytes.
  • $_FILES[“photo”][“tmp_name”] — This array value specifies the temporary name including the full path that is assigned to the file once it has been uploaded to the server.
  • $_FILES[“photo”][“error”] — This array value specifies error or status code associated with the file upload, e.g. it will be “0” if there is no error.

Please get connected & share!

Advertisement