PHP ยท Chapter 30 of 44

PHP File Upload

PHP handles file uploads through the $_FILES superglobal, which is populated when an HTML form uses enctype="multipart/form-data" and includes a file input field.

Uploaded files are temporarily stored on the server, and you must use move_uploaded_file() to move them to a permanent location. Always validate file type and size before accepting an upload to keep your application secure.

Syntax
<form enctype="multipart/form-data" method="post">
  <input type="file" name="photo">
</form>

The upload form

The form must include enctype="multipart/form-data" and method="post" for file uploads to work correctly, along with an <input type="file"> element.

Processing the upload

$_FILES["fieldname"] contains details like tmp_name, name, size and error. move_uploaded_file() moves the temporary file to a permanent destination folder.

Example 1 (php)
<?php
  // Assuming a valid upload named "photo"
  $target = "uploads/" . basename($_FILES["photo"]["name"]);
  if (move_uploaded_file($_FILES["photo"]["tmp_name"], $target)) {
    echo "Upload successful";
  }
?>
Output
Upload successful

move_uploaded_file() moves the temporary uploaded file to the uploads folder.

Example 2 (php)
<?php
  $allowed = ["jpg", "png"];
  $ext = strtolower(pathinfo($_FILES["photo"]["name"], PATHINFO_EXTENSION));
  echo in_array($ext, $allowed) ? "Allowed type" : "Invalid type";
?>
Output
Allowed type

Checking the file extension against an allow-list helps prevent unwanted file types from being uploaded.

Key points

  • $_FILES holds information about uploaded files.
  • The form needs enctype="multipart/form-data" to support file uploads.
  • move_uploaded_file() saves the uploaded file to a permanent location.
  • Always validate file type and size before accepting an upload.
๐Ÿ’ก Note: Never trust the uploaded file's original extension alone โ€” also check its actual content type for security.

๐Ÿ“ Quick Quiz

1. Which superglobal holds uploaded file data?

2. What form attribute is required for file uploads?

3. Which function moves an uploaded file to a permanent location?