PHP | Uploading File

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.
Let’s make an HTML form for uploading the file to the server.
index.html

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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.");        
      
        // 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"]." is already exists.";
              
            else
            {
                move_uploaded_file($_FILES["photo"]["tmp_name"],  
                           "uploads/".$_FILES["photo"]["name"]);
                echo "Your file was uploaded successfully.";
            
        
        else
        {
            echo "Error: Please try again."
        }
    
    else
    {
        echo "Error: ". $_FILES["photo"]["error"];
    }
}
?>

chevron_right


In the above script, once we submit the form, later we can access the information via a PHP superglobal associative array $_FILES. Apart form 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 POST then it will proceed otherwise the system will throw an error. Later on, we have 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 temporary location to the desired directory on the server and we are done.
Output



My Personal Notes arrow_drop_up

Worked as a full stack developer in three projects as well as a freelancer with 47/5 rating and 100% completion rate

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.