PHP File Upload

We’ll learn about the PHP file upload process in this chapter. With just a few lines of code, PHP allows you to upload single or many files.

Configure The “php.ini” File

First, make sure PHP is set up to accept file uploads.

Look for the file uploads directive in your “php.ini” file and turn it on.

file_uploads = On

Create HTML Form

Create an HTML form that allows users to select the picture file they’d like to upload next:

<!DOCTYPE html>
<html>
<body>

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

</body>
</html>
PHP File Upload

Here are some guidelines to follow when filling out the HTML form above:

  • Make sure the form’s method=”post” is used.
  • The following attribute is also required for the form: enctype=”multipart/form-data”. When submitting the form, it defines which content-type to utilise.

Note: The input field is displayed as a file-select control with a “Browse” button next to it, due to the type=”file” property of the input> tag.

The input types are discussed in detail in chapter HTML input types.

The html form created above is sent to a file called “file_upload.php,” which we’ll make next.

PHP $_FILES

Before creating Php File upload script, Lets discuss php $File Variable.

The PHP global $_FILES array holds all of the file’s information. We can get the file name, file type, file size, temp file name, and errors related the file using the $_FILES global.

$_FILES[‘filename’][‘name’]returns file name.
$_FILES[‘filename’][‘type’]returns MIME type of the file.
$_FILES[‘filename’][‘size’]returns size of the file (in bytes).
$_FILES[‘filename’][‘tmp_name’]returns the temporary file name of the file which was stored on the server.
$_FILES[‘filename’][‘error’]returns error code associated with this file.

Create The Upload File PHP Script

The code for uploading a file is in the “file_upload.php” file:

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

Note: We can upload files with a variety of extensions.

PHP Code explanation:

  • $target dir = “images/” – defines the destination directory for the uploaded file. Make sure that the directory images exit in nyour computer so that uploaded files can be saved in that folder.
  • The path of the file to be uploaded is specified by $target file.
  • $uploaded=1 has yet to be used in later checks.
  • The file extension is stored in $imageFileType (in lower case).

We can now add some constraints depend on requirements.

Check if File Already Exists

We’ll start by seeing if the file is already in the “uploads” folder. If it does, $uploaded is set to 0 and an error message is displayed:


if (file_exists($target_file)) {
  echo "Ops!!!, file already exists.";
  $uploaded= 0;
}

Limit File Type

Users can only upload JPG, JPEG, PNG, and GIF files using the code below. Before setting $uploaded to 0 for all other file kinds, an error message appears:

if($FileType != "jpg" && $FileType != "png" && $FileType != "jpeg"
&& $FileType != "gif" ) {
  echo "Only JPG, JPEG, PNG & GIF files are allowed.";
  $uploaded = 0;
}

Limit File Size

“fileUpload” is the name of the file input box in our HTML form above.

Now we’re going to look at the file’s size. An error message is produced if the file is larger than 500KB, and $uploaded is set to 0:

if ($_FILES["fileUpload"]["size"] > 500000) {
  echo "Your file is too large.";
  $uploaded = 0;
}

Now lets merge these checks with our main code:

PHP File Upload Complete Code

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

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

// Check file size
if ($_FILES["fileUpload"]["size"] > 500000) {
  echo "Your file is too large.";
  $uploaded = 0;
}

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

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