PHP
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
162: Building a File Upload API with Validation
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
finfoto allow onlyimage/jpeg,image/png, andimage/gif. Reject all other types regardless of their extension. - Filename Randomization: Save the file using a randomly generated string (e.g., using
uniqid()orrandom_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.
There are no comments for now.