Skip to content
Related Articles

Related Articles

PHP | Uploading File

Improve Article
Save Article
  • Difficulty Level : Hard
  • Last Updated : 10 Jun, 2022
Improve Article
Save Article

Have you ever wondered how websites build their system of file uploading in PHP? Here we will come to know about the file uploading process. A question which you can come up with – ‘Are we able to upload any kind of file with this system?’. The answer is yes, we can upload files with different types of extensions. 

Approach: To run the PHP script we need a server. So make sure you have the XAMPP server or WAMP server installed on your windows machine.

HTML code snippet: Below is the HTML source code for the HTML form for uploading the file to the server. In the HTML <form> tag, we are using “enctype=’multipart/form-data” which is an encoding type that allows files to be sent through a POST method. Without this encoding, the files cannot be sent through the POST method. We must use this enctype if you want to allow users to upload a file through a form.

index.html:

HTML




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>File Upload Form</title>
</head>
<body>
    <form action="file-upload-manager.php" method="post" enctype="multipart/form-data">
    <!--multipart/form-data ensures that form data is going to be encoded as MIME data-->
        <h2>Upload File</h2>
        <label for="fileSelect">Filename:</label>
        <input type="file" name="photo" id="fileSelect">
        <input type="submit" name="submit" value="Upload">
        <!-- name of the input fields are going to be used in our php script-->
         
<p><strong>Note:</strong>Only .jpg, .jpeg, .png formats allowed to a max size of 2MB.</p>
 
    </form>
</body>
</html>


Now, time to write a PHP script which is able to handle the file uploading system. file-upload-manager.php 

PHP




<?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_ext = array("jpg" => "image/jpg",
                            "jpeg" => "image/jpeg",
                            "gif" => "image/gif",
                            "png" => "image/png");
        $file_name = $_FILES["photo"]["name"];
        $file_type = $_FILES["photo"]["type"];
        $file_size = $_FILES["photo"]["size"];
     
        // Verify file extension
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
 
        if (!array_key_exists($ext, $allowed_ext))       
            die("Error: Please select a valid file format.");
         
        // Verify file size - 2MB max
        $maxsize = 2 * 1024 * 1024;
 
        if ($file_size > $maxsize)       
            die("Error: File size is larger than the allowed limit of 2MB");       
     
        // Verify MYME type of the file
        if (in_array($file_type, $allowed_ext))
        {
            // Check whether file exists before uploading it
            if (file_exists("upload/".$_FILES["photo"]["name"]))           
                echo $_FILES["photo"]["name"]." already exists!";
             
            else
            {
                move_uploaded_file($_FILES["photo"]["tmp_name"],
                        "uploads/".$_FILES["photo"]["name"]);
                echo "Your file uploaded successfully.";
            }
        }
        else
        {
            echo "Error: Please try again!";
        }
    }
    else
    {
        echo "Error: ". $_FILES["photo"]["error"];
    }
}
?>


In the above script, once we submit the form, later we can access the information via a PHP superglobal associative array $_FILES. Apart from using the $_FILES array, many in-built functions are playing a major role. After we are done with uploading a file, in the script we will check the request method of the server, if it is the POST method then it will proceed otherwise the system will throw an error. Later on, we accessed the $_FILES array to get the file name, file size, and type of the file. Once we got those pieces of information, then we validate the size and type of the file. In the end, we search in the folder, where the file is to be uploaded, for checking if the file already exists or not. If not, we have used move_uploaded_file() to move the file from the temporary location to the desired directory on the server and we are done. 

Output:

 

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!