PHP | Uploading File - GeeksforGeeks

12 May, 2018
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
<!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// Check if the form was submittedif($_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"];    }}?>
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
PHP-file-handling
PHP
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
How to execute PHP code using command line ?
How to pop an alert message box using PHP ?
PHP in_array() Function
How to convert array to string in PHP ?
Installation of Node.js on Linux
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
File uploading in React.js
How to set input type date in dd-mm-yyyy format using HTML ?