File Uploading in PHP

File Uploading in PHP
File Uploading in PHP

File uploading is a common functionality in many applications. In this tutorial, we’ll see how file uploading in PHP works.

In this post, we’ll see how we can upload files using PHP. In the next post we will see how can we upload an image using an ajax?

Uploading files requires following steps-

  • Select a file to be uploaded.
  • Validate uploaded file.
  • Move uploaded file from temporary location to desired location.
  • Show the success message of the uploaded file to the user.

Let’s look into working example first and then we’ll look into its detail-

HTML Form

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload File in PHP</title>
</head>

<body>
    <form action="" method="post" enctype="multipart/form-data">
        <label for="file">Select File:</label>
        <input type="file" name="fileUpload" id="fileUpload">
        <input type="submit" value="Upload File" name="submit">
    </form>
</body>

</html>

In the above code, we have defined form with two tags-

  • Input field with type=”file” will generate browse button to select a file
  • Input field with type=”submit” will generate submit button to submit form.
  • form tag is used to specify form in the HTML document with enctype=”multipart/formdata”

enctype is the encoding type for our form and “multipart/formdata” is used when we need to upload any file.

There are other enctype as well. Listed as below-

  • text/plain : In this type spaces are converted to + sign and no special characters are encoded.
  • application/x-www-form-urlencoded : It is the Default behavior. spaces are converted into + sign and other special characters are converted to ASCII HEX values

PHP Code – File Uploading in PHP

<?php
/* define project root directory */
define('PROJECT_ROOT', dirname(__FILE__));
/* define file upload directory */
define('UPLOAD_DIRECTORY', 'assets/uploads/');

// check if the form is submitted
if (isset($_POST["submit"])) {

    $uploaded_file = UPLOAD_DIRECTORY . basename($_FILES["fileUpload"]["name"]);

    // Check if file is writable
    if (!is_writable(dirname(PROJECT_ROOT . '/' . $uploaded_file))) {
        die("Directory is not writable.");
    }

    $fileType =  strtolower($_FILES["fileUpload"]["type"]);

    // Check if uploaded files are of certain types or not
    if (!in_array($fileType, array("application/msword", 
                                   "application/pdf", 
                                   "application/vnd.ms-excel", 
                                   "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))) {
        die("Only doc, docx, xls & xlsx files are allowed.");
    }

    // Check file size
    if ($_FILES["fileUpload"]["size"] > 500000) {
        die("Uploaded file is too large.");
    }

    if (move_uploaded_file($_FILES["fileUpload"]["tmp_name"], $uploaded_file)) {
        echo "The file " . basename($_FILES["fileUpload"]["name"]) . " has been uploaded.";
    } else {
        echo "There is an error while uploading file.";
    }
}
?>

Let’s understand above PHP code line by line-

First we have defined Two constants using define() function.

  • PROJECT_ROOT : Set the path till the our project is located.
  • UPLOAD_DIRECTORY : Set the upload directory where file will be uploaded.

In the very next line, we checked where the form is submitted using isset($_POST["submit"]) code. This will check if the $_POST array contains submit key is set or not. When the form is not submitted then this piece of code will not be executed & it will show the form to the user.

Next, we have defined a variable to set the uploaded file path in the variable $uploaded_file. This variable will contains a path from the current folder till the image. We will evaluate this value in the next line.

Now, we’ll check if the provided file path is writable or not using is_writable() function. If that file path is correct and file folder is writable then it will move to the next condition.

Next, we’ll get the file type using PHP global variable $_FILES and will evaluate it if that is of types OR not. If those are not of the mentioned file types then it will show an error to the user.

We can also use accept attribute of the input field to allow only specified MIME type. But user can easily manipulate it by editing HTML in developer tool of browser

/* Example of Input  */

<input type="file" accept="application/msword, application/pdf" />

Here, is the list of multi-dimentional array that keeps all the related information about uploaded file

  • $_FILES[‘file’][‘tmp_name’] − File stored in the temporary directory on the web server.
  • $_FILES[‘file’][‘name’] − Actual name of the file.
  • $_FILES[‘file’][‘size’] − Size of uploaded file in bytes.
  • $_FILES[‘file’][‘type’] − MIME type of the file.
  • $_FILES[‘file’][‘error’] − Error code associated with this file upload.

Next, we’ll check if the file size is not greater than 5MB. And if the file size is greater than that then it will show an error to the user

And finally, using move_uploaded_file() function (which takes Two parameters as file and destination). Once the file is uploaded to the respective location then we will show the success message to the user.

Well, this is a very basic example of uploading files. But in a real-world application the code may be too big. It may look difficult/complicate in the first instance. But the approach remains the same.

Now we’ve understood how file upload works in PHP. Let’s see other important configurations that will be helpful while doing the above operation.

When we check phpinfo() then we get useful information stored in it. It shows all the configuration that actually works behind the scene. php.ini file is responsible for storing all the configuration.

Allow HTTP file uploads
file_uploads = On

Apart from this main configuration few of such configurations that are useful in file uploading are as follows-

  • upload_tmp_dir: Directory responsible for storing files temporarily before moving to its desired location.
  • upload_max_filesize: This parameter also defines the maximum size of the file.
  • max_file_uploads: It sets how many files that can be uploaded at a single request. e.g., 20, 30 etc. To upload multiple at a single request we need to use <input type=”file” multiple> attribute in the field declaration.
  • post_max_size: It denotes the maximum size of POST data that PHP will accept.

All these configurations can be set as per the requirement. If you have a dedicated server and has SSH access then you can do that manually after which we need to restart the apache server to reflect it. On the other hand, if we have a shared hosting then it is hard to change these configuration as in this type of sharing we don’t have an access to make such changes. In such case we can use ini_set() function to change such configs on the fly.

Conclusion:

As discussed, we have seen how we can upload any file using PHP and also saw different configurations useful while doing so. In the example, we saw step by step procedure about the file upload.

One Comment

jaya June 20, 2020

Thanks a lot for sharing such a good source with all, i appreciate your efforts taken for the same. I found this worth sharing and must share this with all.