DEV Community

Gilad David Maayan
Gilad David Maayan

Posted on

File Upload in PHP: Tips and Tricks

What is PHP File Upload?

A PHP file upload process enables users to upload files to a server. It involves using a HTML form to upload files into a temporary directory and then using a PHP script to relocate them to a target destination.

Your php.ini configuration file has two parameters that are important for file uploads:

upload_tmp_dir—the temporary directory used for file uploads 
upload_max_filesize—the maximum allowed size of uploaded files
Enter fullscreen mode Exit fullscreen mode

Here is how a minimal file upload process works in PHP:

1.The user opens a page that contains a HTML form with a text file browse button and a submit button.

  1. The user clicks the browse button and chooses a file to upload from their local device.
  2. The full path to the chosen file appears in the text field.
  3. The user clicks the submit button.
  4. The file is sent to the temporary directory on the server defined in upload_tmp_dir.
  5. The PHP script specified as the form handler in the form's action attribute verifies that the file arrived. It then copies the file into a target directory.
  6. The PHP script provides the user with confirmation of a successful upload.

Read this blog post for more background on how file upload works in PHP.

Tutorial: Create a PHP File Uploader

This tutorial will show you how to create a simple PHP script that allows users to upload files to your own web server.

Prerequisites:

  • Install a web server
  • Install a recent version of PHP
  • Create a folder for the uploader project in the root directory of your website (for tutorial purposes only—when enabling file upload in production, uploaded files should preferably be stored outside your root directory)
  • In the project folder, create an upload_data directory—user files will be stored here.
  • Ensure you have available storage space on the web server for uploaded files

Step 1: Create HTML file upload form
First, we need to take care of the client-side code in HTML and create a form that’ll allow users to select files for uploading. Create an index.html file in your project folder and add the following element to it:

<form action="uploader.php" method="post" enctype="multipart/form-data">
Select file for upload:
<input type="file" name="userFile" id="userFile">
<input type="submit" value="Submit" name="submit">
</form>

In the action attribute we refer to the uploader.php script described in the following section.

Step 2: Create PHP upload script
Create a script in your project folder called uploader.php.

`<?php
`
`$currentFolder = getcwd();
$uploadFolder = "/upload_data/";
$uploadApproved = true;

$fileName = $_FILES['fileToUpload']['name'];
$fileSize = $_FILES['fileToUpload']['size'];
$fileTmpName  = $_FILES['fileToUpload']['tmpName'];
$fileType = $_FILES['fileToUpload']['type'];
$fileExtension = strtolower(end(explode('.',$fileName)));`

`$uploadPath = $currentFolder . $uploadFolder . basename($fileName);

if ($uploadFolder . basename($fileName) {
    echo "File already exists.";
    $uploadApproved = false;
}

if ($uploadApproved == false) {
    echo "Error uploading the file.";

} else {
    if (move_uploaded_file($fileTmpName, "$uploadPath")) {
        echo basename($fileName). " has been uploaded.";
    } else {
        echo "Error uploading the file.";
    }
}

?>`

Enter fullscreen mode Exit fullscreen mode

Here are the important elements of this code:

  • The $_FILES object will be populated by the file the user provides once they submit the form. We use it to get basic information about the file—name, type, size, and tmp_name—the temporary name with which it was saved to the PHP server.
  • We define the uploadApproved variable to enable validations on the file being uploaded. Here we perform only one basic validation—that the file does not already exist in the folder. Below are additional validations you can implement.
  • The final else statement moves the file from the PHP temporary directory to the required upload path, and notifies the user if the file was successfully uploaded.

Step 3: Optional validations
It is very important, both for security and operational reasons, to validate and restrict the files being uploaded. Here are a few validations you can add to the basic script above:

  • Defining a whitelist of file extensions
  • Defining a maximum file size (note that php.ini already defines a global maximum for file upload size, you can define a lower value in your script)
  • Scanning the file for malware. For example, you can use the open source library PHP-Antimalware-Scanner to scan your uploaded files.

For example, here is how to limit file size to 10 MB:

if ($fileSize > 10000000) {
$uploadApproved = false;
}

File Uploading Tips and Best Practices

Cloud Storage
For small scale applications, uploading files directly to your server might work well. However, as you scale up, you will find that user uploads take up valuable storage space. Allowing users to upload files directly to your website root directory also raises security concerns.

To alleviate these problems, it is easy to set up a cloud storage account and move user uploads from the temporary PHP upload folder directly to the cloud. Read this blog for more background on cloud storage systems.

Drag and Drop
Today, most web interfaces offer a drag and drop file upload functionality. Drag and drop often translates into a positive user experience because it enables users to easily choose a file from an open folder and then drag and drop it into the web page. Drag and drop offers a convenient file uploading experience.

Uploading From a Variety of Sources
Users typically upload files from their device storage. You can integrate various upload sources to make the file uploading process convenient for many users. Common sources include local webcams, social media sites, remote URLs, cloud storage, and services like Flickr and Evernote. You can add many options or choose the relevant sources for the site’s users.

Safe Uploads
Adding file uploading functionality means your site accepts user-generated content. As a result, the site is exposed to potential risks, such as malicious software (malware), attacks on user data, unauthorized server access, and illegal file hosting. You can prevent these risks by validating the site’s file upload form in various methods.

You can create an allowlist that specifies the types of files allowed for upload and those the site must reject. Before allowing upload, the site should verify the file type against the allowlist. You should also scan uploaded files using anti-malware tools and set up SSL encryption to secure data in transit. Setting a minimum and maximum file size range can help you prevent service outages.

In-browser Image Editing
Sometimes users need to edit images to fit the design of the app or site before uploading the file. Ideally, a file uploader should provide the functionality to perform various manipulations, such as crop, rotate, resize, mirror, invert, blur, and enhance, by using the browser.

Advanced features may include face and object detection. This functionality can automatically perform various tasks. For example, it can focus on a person’s face in an image and crop the photo to the shape and size suitable for a thumbnail.

Conclusion

In this article, I provided a quick tutorial showing how to create a simple PHP application with file upload functionality. This involves:

  1. Creating an HTML upload form
  2. Writing a PHP upload script
  3. Performing optional validations to verify file size, type, etc.

In addition, I provided some best practices that can make file upload more attractive to users:

  • Drag and drop interface
  • Multiple file sources
  • Secure uploads
  • In-browser image editing I hope this will be useful as you add a robust file upload mechanism to your next PHP project.

Top comments (0)