Current Location: Home> Latest Articles> PHP File Upload Tutorial: How to Upload Files in PHP

PHP File Upload Tutorial: How to Upload Files in PHP

M66 2025-11-01

PHP File Upload Tutorial: How to Upload Files in PHP

Uploading files in PHP requires following several steps: creating an HTML form, processing the uploaded file, moving the file to a permanent location, adding security checks, and handling errors. In this tutorial, we will walk through each step in detail.

Creating the HTML Form

First, you need to create an HTML form that allows the user to select the file they want to upload. The form should include an input element of type file:

<form action="upload.php" method="post" enctype="multipart/form-data">
  <input type="file" name="file">
  <input type="submit" value="Upload File">
</form>

Processing the Uploaded File

After the form is submitted, PHP stores the file temporarily. You can access information about the uploaded file using the $_FILES array, such as its name, size, and temporary path:

<?php
$file = $_FILES["file"];

if ($file["error"] === UPLOAD_ERR_OK) {
  // File uploaded successfully
  // Continue processing the file
} else {
  // Handle upload errors
}
?>

Moving the File to a Permanent Location

If the file was uploaded successfully, you need to move it to a permanent storage location. For example:

move_uploaded_file($file["tmp_name"], "uploads/" . $file["name"]);

Adding Security Checks

When uploading files, always perform security checks. You can scan the file for viruses or malicious software, and validate the file type and size to enhance security.

Handling Errors

During the upload process, different types of errors may occur. You can check the value of $_FILES["file"]["error"] to determine the error type. Common error codes include:

  • UPLOAD_ERR_OK: No errors occurred.
  • UPLOAD_ERR_INI_SIZE: The file is too large, exceeding the maximum file size in PHP configuration.
  • UPLOAD_ERR_FORM_SIZE: The file is too large, exceeding the maximum file size set by the HTML form.
  • UPLOAD_ERR_PARTIAL: The file was only partially uploaded.
  • UPLOAD_ERR_NO_FILE: No file was selected.

This concludes the steps for uploading files in PHP. By following these practices, you can ensure a secure and stable file upload process in your PHP applications.