PHP File Upload

PHP can receive files from a form, like a profile photo or a PDF. The steps are: create a form that can send files, receive the file in PHP, check it, and move it to its final folder.


Step 1: HTML form

Two things are needed: the method must be post, and the form must have enctype="multipart/form-data". Without it the file is not sent.

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

Step 2: the $_FILES array

PHP saves the uploaded file in a temporary folder and gives its details in $_FILES["photo"].

KeyMeaning
nameThe original file name from the user computer
typeThe type sent by the browser (not reliable)
tmp_nameThe temporary path on the server
errorError code, 0 (UPLOAD_ERR_OK) means success
sizeSize in bytes

Step 3: upload.php

<?php
if ($_FILES["photo"]["error"] !== UPLOAD_ERR_OK) {
    exit("Upload failed.");
}

// Allow only small images
$allowed = ["image/jpeg" => "jpg", "image/png" => "png"];

$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($_FILES["photo"]["tmp_name"]);

if (!isset($allowed[$mime])) {
    exit("Only JPG and PNG files are allowed.");
}

if ($_FILES["photo"]["size"] > 2 * 1024 * 1024) {
    exit("File is too big. Maximum 2 MB.");
}

// Create a safe new name
$newName = bin2hex(random_bytes(16)) . "." . $allowed[$mime];

if (move_uploaded_file($_FILES["photo"]["tmp_name"], __DIR__ . "/uploads/" . $newName)) {
    echo "File uploaded successfully.";
} else {
    echo "Could not save the file.";
}
?>

Output:

Tutorials Class - Output Window

File uploaded successfully.

  • move_uploaded_file() moves the file from the temporary folder. It works only for files uploaded by PHP.
  • The folder uploads must exist, and PHP must have permission to write in it.
  • The temporary file is deleted automatically at the end of the script if you do not move it.

Upload limits in php.ini

If a big file does not upload, check the limits upload_max_filesize and post_max_size. See the maximum upload size and how to increase it.


Security rules

  • Never trust the file name or the type sent by the browser. Check the real type, as in the example.
  • Rename the file, and do not use the original name.
  • Do not allow PHP or other executable files.
  • Save the files outside the public folder if you can.

A full list is in how to upload a file securely in PHP and PHP Security Tips.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.