PHP File Upload

This tutorial helps you learn how to upload files easily. Let us first understand what PHP File Upload is?

 

What is PHP File Upload?

With PHP, files can be easily uploaded to the server. However, you must always be careful when allowing file uploads!

 

Configure The "php.ini" File

First, make sure that PHP is configured to permit file uploads.

For this, search for the file-uploads directive in your "php.ini" file and set it to On: 

file_uploads = On

 

Create The HTML Form

Now, you need to create an HTML form that will allow users to select the image file they want to upload:

<!DOCTYPE html>
<html>
<body>

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

</body>
</html>

 

You need to follow some rules for the HTML form above:

  • Ensure that the form is using the method="post"
  • The form also requires the following attribute: enctype="multipart/form-data". It lets you specify which content-type to use during form submission
  • The file upload will not work without the requirements above.


    Other points to remember:
  • The <input> tag's type="file" attribute shows the input field as a file-select control, along with a "Browse" button right next to the input control.

 

The above-mentioned form will send data to a file known as "upload.php", which we will create in the next section.

 

Create The Upload File PHP Script

The "upload.php" file includes the code for uploading a file:

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
  $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
  if($check !== false) {
    echo "File is an image - " . $check["mime"] . ".";
    $uploadOk = 1;
  } else {
    echo "File is not an image.";
    $uploadOk = 0;
  }
}
?>

Describe the above PHP script:

  • $target_dir = "uploads/" - It is for specifying the directory where the file is will be placed
  • $target_file- It is for specifying the path of the file that is to be uploaded
  • $uploadOk=1- It means it is not yet used (will be used later)
  • $imageFileType- It holds the file's file extension (in lower case)
  • Next, it needs to be checked if the image file is a fake image or an actual image

 

Check if File Already Exists

Some restrictions can also be added.

First, check if the file is already there in the "uploads" folder. If yes, an error message is displayed, and $uploadOk is set to 0:

// Check if file already exists
if (file_exists($target_file)) {
  echo "Sorry, file already exists.";
  $uploadOk = 0;
}

 

Limit File Size

In the above-mentioned HTML form, the file input field is named "fileToUpload".

Now, check the file size. In case the file is larger than 500KB, then an error message will be displayed, and $uploadOk is set to 0:

// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
  echo "Sorry, your file is too large.";
  $uploadOk = 0;
}

 

Limit File Type

The code given below only lets users upload JPEG, JPG, GIF, and PNG files. All other file types will give an error message before setting $uploadOk to 0:

// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
  echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
  $uploadOk = 0;
}

 

Now combine all PHP code.

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

// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
  $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
  if($check !== false) {
    echo "File is an image - " . $check["mime"] . ".";
    $uploadOk = 1;
  } else {
    echo "File is not an image.";
    $uploadOk = 0;
  }
}

// Check if file already exists
if (file_exists($target_file)) {
  echo "Sorry, file already exists.";
  $uploadOk = 0;
}

// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
  echo "Sorry, your file is too large.";
  $uploadOk = 0;
}

// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
  echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
  $uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
  echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
  if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
    echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
  } else {
    echo "Sorry, there was an error uploading your file.";
  }
}
?>