File Upload in PHP with an Example

File upload functionality has become a standard feature of many websites and applications in the digital age. Whether it's images, documents, or videos, file upload allows users to quickly and easily share their content with others.

PHP has long been a popular web development language for creating dynamic websites, and its file upload capabilities are no exception. Developers can create a seamless file upload experience for their users using PHP's robust set of features and functions. So, whether you're creating a social media platform or a document management system, knowing how to upload files in PHP is a must-have skill for any web developer.

In this article, we'll delve into the world of PHP file upload, covering everything from fundamental concepts to advanced techniques, so you can create powerful and user-friendly file upload features for your web applications.

You may need to modify the "php.ini" file depending on your server configuration before you can upload files of a certain size. PHP by default restricts the size of uploaded files to 2MB. If you need to allow users to upload larger files, you can change the following settings in the "php.ini" file:

upload_max_filesize = 10M
post_max_size = 10M

In this illustration, the 10MB upload limit has been set. This value can be changed to suit your requirements. Another thing to clarify is whether the "file_uploads," that is:

file_uploads = On

is set.

PHP file upload example

In this section, I'll demonstrate how to upload a file in PHP. So, before we get into the example, let me first explain that we need to create a folder called "uploads" or whatever you want to call it in order to upload all of the files in this separate folder.

I'm going to make two files: one called "index.php" that contains the HTML code for implementing the file upload form, and another called "upload.php" that contains the PHP script that handles the file upload form written in "index.php" and sends or uploads the file to the folder "uploads." Consider the following snapshot to help you understand:

php file upload files and folders

It's time to start writing HTML code for the "index.php" file. I just wrote the following, which is provided below:

<!DOCTYPE html>
<html>
<body>

   <form action="upload.php" method="post" enctype="multipart/form-data">
      Choose an image to upload:
      <input type="file" name="file">
      <input type="submit" value="Upload Image" name="submit">
   </form>

</body>
</html>

The output should be:

php file upload form example

Now, click on the "Choose file" button, select a file, such as an image, and then click on the "Open" or similar type of button, as shown in the screenshot below:

php file upload choosing file example

Now that I've selected the file, here's how the output of the file upload form has changed. You can see that the filename I just chose is displayed.

php file upload file choose example

Let's write the PHP script to handle and upload the selected image before clicking the "Upload Image" button. I just wrote the following script for the "upload.php" file:

<?php
   $target_dir = "uploads/";
   $target_file = $target_dir . basename($_FILES["file"]["name"]);
   $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

   // upload file
   if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
      echo "The file ". htmlspecialchars( basename( $_FILES["file"]["name"])). " has been uploaded.";
   } else {
      echo "There was an error while uploading your file.";
   }
?>

When I click on the "Upload Image" file, I am redirected to the "upload.php" page, which uploads the selected file and outputs the following data:

php file upload file uploaded example

If you open the "uploads" folder, you will find the file there.

php file upload example

File uploads in PHP can be dangerous at times

Before implementing a file upload script in your PHP application, there are several considerations to make:

These considerations, however, are entirely dependent on the requirements. But I'm going to change the "upload.php" script in such a way that it only allows the image file to be uploaded in a specific image file format. It determines whether the file's size is correct. It also determines whether the file already exists, and, then determines the file's size. I modified the "uploads.php" script with these considerations in mind. However, you can still make some other changes based on your needs.

<?php
   $targetDirectory = "uploads/";
   $targetFile = $targetDirectory . basename($_FILES["file"]["name"]);
   $uploadOk = 1;
   $imageFileType = strtolower(pathinfo($targetFile,PATHINFO_EXTENSION));

   // Determine whether the image file is genuine or a fake one.
   if(isset($_POST["submit"])) {
      $check = getimagesize($_FILES["file"]["tmp_name"]);
      if($check !== false) {
         echo "<p>File is an image: <b>" . $check["mime"] . "</b>.</p>";
         $uploadOk = 1;
      } else {
         echo "<p>File is not an image.</p>";
         $uploadOk = 0;
      }
   }

   // Check to see if the file already exists.
   if (file_exists($targetFile)) {
      echo "<p>Sorry, but the file already exists.</p>";
      $uploadOk = 0;
   }

   // Examine the file size
   if ($_FILES["file"]["size"] > 500000) {
      echo "<p>Unfortunately, your file is too large.</p>";
      $uploadOk = 0;
   }

   // Allow specific file formats
   if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
      echo "<p>Only JPG, JPEG, PNG, and GIF files are permitted.</p>";
      $uploadOk = 0;
   }

   // Check if $uploadOk is set to 0 by an error
   if ($uploadOk == 0) {
      echo "<p>Sorry, your file was not uploaded.</p>";
      // If everything is in order, try to upload the file.
   } else {
      if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile)) {
         echo "<p>The file <b>". htmlspecialchars( basename( $_FILES["file"]["name"])). "</b> has been uploaded.</p>";
      } else {
         echo "<p>There was an error while uploading your file.</p>";
      }
   }
?>

If you try to upload the output now, you will get the following output if it is successful:

file upload in PHP

PHP Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!