Skip to Content
Course content

162: Building a File Upload API with Validation

Click on the "Edit" button in the top corner of the screen to edit your slide content.

File uploads are one of those features that feel trivial until you realize you've essentially just opened a door to your server and invited any stranger to leave a package inside. When I first started building APIs, I treated $_FILES as a trusted source of truth. I'd see a .jpg extension and assume it was a photo. That's a mistake that can lead to a full server compromise in about thirty seconds if someone uploads a PHP script disguised as an image.

The danger of trusting the user's label

Let's look at the naive way to handle a profile picture upload. In this version, the developer trusts the name provided by the browser and just moves the file into an uploads folder.

// The "I hope no one is malicious" approach
$targetDir = "uploads/";
$fileName = basename($_FILES["profile_pic"]["name"]);
$targetFilePath = $targetDir . $fileName;

if (move_uploaded_file($_FILES["profile_pic"]["tmp_name"], $targetFilePath)) {
    echo "Upload successful!";
}

On the surface, this works. But look at what's happening. I'm using the filename provided by the client. If a user uploads a file named shell.php, and my server is configured to execute PHP in the uploads directory, they can now run arbitrary code on my machine. Even if I add a simple check like if (pathinfo($fileName, PATHINFO_EXTENSION) == 'jpg'), a clever attacker can name a file malicious.jpg.php or just spoof the extension while the content remains a script. I've essentially given the user the ability to write files to my disk with their own naming convention. That's a nightmare.

Validating content, not extensions

To do this properly, we have to stop looking at the filename and start looking at the file's actual bytes. We use the finfo (File Information) extension to determine the MIME type. This reads the "magic bytes" at the start of the file to see what it actually is, regardless of what the extension says.

I also want to ensure the file isn't massive—otherwise, a user could fill up my entire disk quota with a single 10GB upload. We should check $_FILES['profile_pic']['size'] against a reasonable limit, like 2MB for an avatar.

$maxSize = 2 * 1024 * 1024; // 2MB
$allowedMimes = ['image/jpeg', 'image/png', 'image/webp'];

if ($_FILES['profile_pic']['size'] > $maxSize) {
    die("File is too large.");
}

$finfo = new finfo(FILEINFO_MIME_TYPE);
$mimeType = $finfo->file($_FILES['profile_pic']['tmp_name']);

if (!in_array($mimeType, $allowedMimes)) {
    die("Invalid file type. Please upload an image.");
}

Now we're getting somewhere. Even if the user renames a PHP script to photo.jpg, finfo will see that it's actually text/x-php and reject it. We've moved from "trusting the label" to "inspecting the goods."

Sanitizing the destination

The final piece of the puzzle is how we store the file. I never, ever keep the original filename. Not only does this prevent the execution attacks I mentioned earlier, but it also prevents "collision" issues where two users upload a file named image.jpg and overwrite each other.

The best approach is to generate a cryptographically secure random name and append the extension based on the validated MIME type, not the user's input. I usually use bin2hex(random_bytes(16)) for this. It's fast, unique, and impossible for a user to guess or manipulate.

$extension = [
    'image/jpeg' => 'jpg',
    'image/png'  => 'png',
    'image/webp' => 'webp',
][$mimeType];

$safeName = bin2hex(random_bytes(16)) . '.' . $extension;
$targetFilePath = "uploads/" . $safeName;

if (move_uploaded_file($_FILES["profile_pic"]["tmp_name"], $targetFilePath)) {
    // Store $safeName in the database linked to the user
    echo "Upload successful!";
}

By combining MIME validation, size limits, and randomized filenames, we've turned a dangerous vulnerability into a robust API endpoint. You've stripped the user of any control over the file system and kept the control firmly in your own hands.




📋 Practical Task

Exercise: Secure Avatar Upload Endpoint

Build a PHP script that handles a POST request containing a file named avatar. Your script must implement the following security requirements:

  • Size Limit: Reject any file larger than 5MB.
  • Content Validation: Use finfo to allow only image/jpeg, image/png, and image/gif. Reject all other types regardless of their extension.
  • Filename Randomization: Save the file using a randomly generated string (e.g., using uniqid() or random_bytes()) and the appropriate extension based on the detected MIME type.
  • Error Handling: Return a clear message if the upload fails or the validation fails.

Test your endpoint by attempting to upload a .txt file renamed to .jpg to ensure your MIME validation is working correctly.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.