All posts
PHPNovember 10, 20268 min read

PHP File Upload for Beginners: Step-by-Step Guide

Learn how to do a PHP file upload step by step. Build a safe image upload form, check size and type, and save files with move_uploaded_file(). Beginner friendly.

F
Fepiq Team
Fepiq

How do you do a PHP file upload? You add a form with a file input, send it with the POST method, and then use PHP's $_FILES variable and the move_uploaded_file() function to save the file on your server. This guide shows each step in plain English, with small examples you can copy and run.

You do not need any experience with uploads. If you already know how forms work, you are ready. If not, read our guide on PHP form handling first.

New to forms? Learn how PHP receives data with GET and POST first.

Read: PHP Form Handling

How a file upload works

When a user picks a file, the browser sends it to your server with the form. PHP puts the file in a temporary folder and tells you about it. Your job is to check the file and move it to a permanent folder. If you do nothing, PHP deletes the temporary file when the script ends.

  1. The user chooses a file in an HTML form.
  2. The browser sends the file with a POST request.
  3. PHP stores it in a temporary location and fills the $_FILES array.
  4. Your code checks the file and moves it to a safe folder.

Step 1: Create the HTML upload form

html
<form action="upload.php" method="post" enctype="multipart/form-data">
  <label for="photo">Choose an image:</label>
  <input type="file" name="photo" id="photo">
  <button type="submit">Upload</button>
</form>

Line 1 sends the form to upload.php using POST. The enctype="multipart/form-data" part is required. Without it, the browser sends only the file name and not the file itself. Line 3 is the file input, and its name (photo) is the key you will use in PHP. Line 4 is the button that sends the form.

Step 2: Read the $_FILES array

$_FILES is a special PHP array that holds information about uploaded files. Save this code as upload.php next to your form.

php
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    if (isset($_FILES["photo"]) && $_FILES["photo"]["error"] === UPLOAD_ERR_OK) {
        echo "Name: " . $_FILES["photo"]["name"] . "<br>";
        echo "Type: " . $_FILES["photo"]["type"] . "<br>";
        echo "Size: " . $_FILES["photo"]["size"] . " bytes<br>";
        echo "Temp path: " . $_FILES["photo"]["tmp_name"];
    } else {
        echo "No file was uploaded or something went wrong.";
    }
}

Line 2 checks that the form was sent with POST. Line 3 checks that a file arrived and that the error code is UPLOAD_ERR_OK, which means no problem. Lines 4 to 7 print four useful facts about the file. If anything is wrong, the else part shows a message.

Here is what each key inside $_FILES["photo"] means:

KeyMeaning
nameThe original file name from the user's computer
typeThe file type the browser claims (not fully trusted)
sizeThe file size in bytes
tmp_nameThe temporary path where PHP stored the file
errorA number; 0 (UPLOAD_ERR_OK) means success

Step 3: Create an uploads folder

Create a folder named uploads next to your PHP file. PHP must be allowed to write to it. On Linux or macOS you can run this in a terminal:

bash
mkdir uploads
chmod 755 uploads

The first line makes the folder. The second line lets the owner read, write and open it, and lets others read and open it. If uploads still fail on your server, check that the web server user owns the folder.

Step 4: Check the file before saving it

Never trust uploaded files. A user could send a huge file or a harmful script instead of a picture. Always check at least two things: the size and the real file type.

  • Size: reject files that are too large.
  • Type: allow only the types you expect, such as JPG and PNG.
  • Name: do not use the original name; create your own.

The type value in $_FILES comes from the browser and can be faked. Use PHP's finfo class instead. It looks at the real content of the file.

Step 5: Save the file with move_uploaded_file()

Here is the complete, safe version of upload.php. It checks errors, size and type, then saves the file with a random name.

php
<?php
$message = "";
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $file = $_FILES["photo"] ?? null;

    if (!$file || $file["error"] !== UPLOAD_ERR_OK) {
        $message = "Upload failed. Please try again.";
    } elseif ($file["size"] > 2 * 1024 * 1024) {
        $message = "File is too large. Maximum is 2 MB.";
    } else {
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $mime = $finfo->file($file["tmp_name"]);
        $allowed = [
            "image/jpeg" => "jpg",
            "image/png"  => "png",
            "image/gif"  => "gif",
        ];

        if (!isset($allowed[$mime])) {
            $message = "Only JPG, PNG and GIF images are allowed.";
        } else {
            $newName = bin2hex(random_bytes(8)) . "." . $allowed[$mime];
            $target = __DIR__ . "/uploads/" . $newName;

            if (move_uploaded_file($file["tmp_name"], $target)) {
                $message = "Success! Saved as " . $newName;
            } else {
                $message = "Could not save the file.";
            }
        }
    }
}
echo htmlspecialchars($message);

Line 3 safely reads the file, using ?? null when nothing was sent. Line 5 handles upload errors. Line 7 rejects files over 2 MB (2 * 1024 * 1024 bytes). Lines 10 and 11 find the real MIME type, such as image/png. The $allowed array lists accepted types and the extension we will use for each. Line 21 builds a random file name, so two users can never overwrite each other and nobody can sneak in a name like shell.php. Line 22 sets the target path. Line 24 calls move_uploaded_file(), which moves the file from the temporary folder to uploads. The last line prints the message safely with htmlspecialchars().

Common upload errors and fixes

ProblemLikely causeFix
$_FILES is emptyMissing enctype on the formAdd enctype="multipart/form-data"
Error code 1 or 2File bigger than the PHP limitRaise upload_max_filesize and post_max_size
move_uploaded_file failsFolder missing or not writableCreate uploads and fix permissions
Wrong type rejectedExtension and content do not matchCheck the real MIME type with finfo

Raising the PHP upload limit

By default PHP often allows only 2 MB per upload. You can change this in your php.ini file:

ini
upload_max_filesize = 8M
post_max_size = 10M
file_uploads = On

upload_max_filesize is the biggest single file. post_max_size is the biggest total request, so keep it a bit larger. Restart your web server after changing php.ini.

Safety checklist

  • Always check the size and the real MIME type.
  • Create your own random file name.
  • Allow only the extensions you need.
  • Never let users upload .php files into a folder that the web server runs.
  • Escape any text you print with htmlspecialchars().

Frequently asked questions

How do I upload a file in PHP?+

Create a form with method="post", enctype="multipart/form-data" and an input of type file. In PHP, read the file from $_FILES and save it with move_uploaded_file(). Always check the size and type first.

Why is my $_FILES array empty?+

The most common reason is a missing enctype="multipart/form-data" on the form. It can also happen when the file is larger than post_max_size, so PHP drops the whole request.

How do I limit the file size in PHP?+

Check $_FILES["photo"]["size"] in your code and reject big files. You can also change upload_max_filesize and post_max_size in php.ini to set server-wide limits.

Is it safe to use the original file name?+

No. The name comes from the user and may contain odd characters or a harmful extension. Create a random name yourself and choose the extension from a list of allowed types.

How do I upload multiple files in PHP?+

Add the multiple attribute and use name="photos[]" on the input. PHP then gives you arrays inside $_FILES["photos"], and you can loop over them with foreach and handle each file the same way.

Want to store uploaded file names in a database? Learn how to insert form data into a database next.

Read: Insert Form Data

Need help building a real web app with file uploads? Talk to the Fepiq team.

Contact Fepiq

Get new posts in your inbox

Occasional, no-fluff notes on shipping modern software — startups, automation, Laravel, Shopify and more. No spam, unsubscribe anytime.

Keep reading

Related posts

All posts

Let's build something

Ready to ship your next product with Fepiq?

Book a free discovery call. We'll listen, ask sharp questions, and send you a proposal within 3 business days.