How to Upload File in PHP (Step by Step)

In this tutorial, you will learn how to upload a file in PHP step by step with the help of examples. File upload is one of the most important features in the modern web applications. It allows users to send files from their computer to the web server through an HTML form. These files are then stored in a specific folder on the server and can be accessed or processed further.

When building a blog system, an e-commerce website, or a user profile system, you may need to allow users to upload files such as images, documents, or videos. For example, blog authors may upload a featured image for an article, e-commerce store owners may upload product images, and a job portal may allow users to upload resumes or CVs.

PHP makes this uploading very simple through the $_FILES superglobal array and the move_uploaded_file() function. So, let’s understand file upload in PHP.

Steps to Upload File in PHP


Uploading files to the server is very simple with PHP. However, simplicity can be dangerous, so be cautious when allowing file uploads. Follow all the simple steps to upload file in PHP:

Step 1: Configure the “php.ini” File

You first make sure that PHP is set up to accept file uploads. In your “php.ini” file, look for the file_uploads directive, and set it on like this:

file_uploads = On

The file_uploads directive tells PHP whether file uploads through HTTP (such as uploading through an HTML form) are allowed or not. By default, it is usually set to On. If it is set to Off, PHP will not accept file uploads at all.

Step 2: Create an HTML Form

To upload any file they want, you need to create an HTML form (index.html) with the following attributes:

  • method=”post” → The POST method sends data securely in the request body. You cannot send file uploads using GET method.
  • enctype=”multipart/form-data” → Without this field, the uploaded file data will not be transmitted. This attribute tells the browser to encode the form data properly, including the file.
  • <input type=”file”> → This field allows the user to browse and select a file from their computer system. You can also use multiple attribute to allow the users for uploading more than one file.

Hence, method=”post”, enctype=”multipart/form-data”, and input type=”file” are the essential fields of an HTML form for uploading files in PHP.

<!DOCTYPE html>
<html>
<head>
    <title>Upload File in PHP</title>
</head>
<body>
   <h4>Upload File</h4>
   <form action="upload.php" method="post" enctype="multipart/form-data">
      <input type="file" name="fileToUpload" id="fileToUpload">
      <button type="submit" name="submit">Upload</button>
   </form>
</body>
</html>

Step 3: PHP Script to Upload File

Now, let’s create an “upload.php” file containing the following code of uploading a single file.

<?php
if (isset($_POST['submit'])) {
 // Create a folder where files will be saved.
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "File " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded successfully.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

The above PHP script is a general script to upload any type of file, such as image, text, pdf, video, etc. The file size is within the PHP limits (upload_max_filesize, post_max_size).

1. if (isset($_POST[‘submit’])) { … }:

  • This checks if the form has been submitted. It looks for a form field (i.e. submit button) with the name submit.
  • If the user clicked the “Upload” button, then the code inside runs.

2. $target_dir = “uploads/”;

  • This defines the folder where files will be stored. This means that your uploaded file will place inside an uploads folder in the same directory as your PHP script.
  • Make sure this folder exists and has write permissions.

3. $target_file = $target_dir . basename($_FILES[“fileToUpload”][“name”]);

  • This builds the full path of the uploaded file.
  • $_FILES[“fileToUpload”][“name”] → This specifies the original name of the uploaded file. $_FILES is a PHP superglobal variable that holds all information about uploaded files.
  • basename() → This is a built-in PHP function that is used to get the filename from a file path. It strips the directory path for security and returns only the file name.

4. move_uploaded_file($_FILES[“fileToUpload”][“tmp_name”], $target_file)

  • When a file is uploaded, PHP always stores uploaded files in a temporary location (or folder like C:/xampp/tmp/) first on the server.
  • $_FILES[“fileToUpload”][“tmp_name”] → This is a temporary file path.
  • move_uploaded_file() → This function safely moves the uploaded file from the temporary folder to your target folder (uploads/).


5. Success and Error Messages

  • If the file moves successfully, it displays a confirmation message: “File scientecheasy.png has been uploaded successfully”.
  • If not, it shows an error message: “Sorry, there was an error uploading your file.”.

Note:

  • You must always create an uploads/ folder (or any target folder you want) inside your project directory.
  • The folder must have proper write permissions so PHP can move the uploaded file into it.
  • On Linux/Mac:
    • 755 → Read/execute for everyone, write for owner (safer).
    • 777 → Read/write/execute for everyone (less secure, only use in local testing).
  • On Windows (XAMPP/WAMP):
    • Right-click the folder → Properties → Security → allow Write permissions.

File Upload with Validation in PHP


If you allow the users to upload files without validation can be risky if you do not handle properly. This is because users might try to upload:

  • Very large files which can crash your server.
  • Executable or malicious files, such as .php, .exe, .js, which could be used for hacking.
  • Incorrect file types like uploading a .txt when you only allow to upload images.

Therefore, you must add validation like file type, size, and errors.

Common and Important Validations in PHP File Upload

When handling file uploads, you should add these checks:

  • You should always validate file type or extensions and MIME types. Only allow specific file formats such as .jpg, .png, .pdf, etc.
  • You should limit the size of file to prevent server overload. For example, you can allow only files less than 2MB.
  • Always check file upload error validation using $_FILES[‘file’][‘error’]. If it’s not 0, then something went wrong like file too big, upload interrupted, etc..
  • Rename files or generate unique names before saving to avoid overwriting of existing files.
  • Ensure uploads/ folder exists and is writable.
  • Store uploaded files outside the web root when possible and serve them through a script that checks permissions.
  • You should restrict executable files like .php, .exe, etc..
  • Perform server-side checks only. You do not rely on client-side validation.
  • Use finfo_file() or getimagesize() for images to verify content, not just extensions.
  • Use HTTPS for uploads to protect files in transit.
  • Scan uploaded files for malware if your application accepts uploads from untrusted users.

These kinds of validations protect your server and ensure only safe files are uploaded.

Example: Upload Image File with Validation

<?php
// Define the target folder where uploaded files will be stored.
$target_dir = "uploads/";
// Set the target file path (uploads/ + filename).
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
// Create a flag to check if file should be uploaded or not.
$uploadOk = 1;

if (isset($_POST['submit'])) {
 // Check if image file is a real 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 in uploads folder.
    if (file_exists($target_file)) {
       echo "Sorry, file already exists.";
       $uploadOk = 0;
    }

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

 // Allow only specific file formats (extensions).
    $fileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
    $allowed_types = array("jpg", "png", "jpeg", "gif");

    if (!in_array($fileType, $allowed_types)) {
       echo "Sorry, only JPG, JPEG, PNG, and GIF files are allowed.";
       $uploadOk = 0;
    }

 // If everything is fine and all checks passed, upload the file.
    if ($uploadOk == 1) {
       if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
            echo "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
       } else {
            echo "Error uploading your file.";
       }
    }
}
?>

What This PHP Code Does?

This PHP script allows the user to upload only image file. It will check the following validations:

  • Checks if the file is a real image using getimagesize().
  • Rejects if the file already exists.
  • Rejects if file size is more than 2MB.
  • Restricts file types to: jpg, jpeg, png, gif.
  • Moves the file from PHP’s temporary folder to your uploads/ folder if all checks pass.

If the file is an image, it will pass. If the file is a PDF or any non-image file, it fails with “File is not an image.”.

Upload docx, pdf, txt Files

If you want to allow the users to upload pdf, docx, and txt files, then you can modify the following code like this:

$allowed_types = array("jpg", "png", "jpeg", "gif", "docx", "pdf", "txt");

Real-Time Use Cases of File Uploading


Following are the real-time use cases of file upload in PHP:

  • User profile picture upload in social media platforms.
  • Resume/CV upload in job portals.
  • Image upload in blogging or CMS systems such as WordPress, Joomla.
  • File sharing applications like Google Drive.
  • E-commerce websites for uploading product images.