File Upload in PHP with Examples [2 Steps]

In this article we are going to cover File Upload in PHP with Examples.

What is file upload in PHP?

PHP allows you to upload single and multiple files through few lines of code only. And it is easy to upload files to the server. PHP file upload features allows you to upload binary and text files both.


In PHP, global $_FILES contains all the information of file. The help of $_FILES global, we can get file name, file type, file size, temp file name.


Returns file name


Returns MIME type of the file.


Returns size of the file in bytes.


Returns temporary file name of the file which was stored on the server.


Returns error code associated with this file.

Create The HTML Form

Next, create a HTML form that allow users to choose the image file they want to upload:

<!DOCTYPE html>
<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">



File Upload in PHP with Examples [2 Steps] 1


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

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;

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

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

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

if ($uploadOk == 0) {
  echo "Sorry, your file was not uploaded.";

} 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.";
File Upload in PHP with Examples [2 Steps] 2


In this article we have covered File Upload in PHP with Examples.

Related Articles:


File Upload in php official page

Shweta Mamidwar

I am Shweta Mamidwar working as a Intern in Product Company. Likes to share knowledge.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share via
Copy link
Powered by Social Snap