Quick Answer
Proper validation and sanitization of uploaded files.
Understanding the Issue
File uploads pose security risks if not properly handled. Always verify file types, sizes, and scan for potential threats.
The Problem
This code demonstrates the issue:
Php
Error
// Problem: Unsafe upload handling
move_uploaded_file($_FILES["file"]["tmp_name"], "/uploads/".$_FILES["file"]["name"]);
The Solution
Here's the corrected code:
Php
Fixed
// Solution 1: Secure upload
$allowed = ["image/jpeg", "image/png"];
$max_size = 2 * 1024 * 1024; // 2MB
if (in_array($_FILES["file"]["type"], $allowed)
&& $_FILES["file"]["size"] <= $max_size) {
$ext = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
$filename = uniqid().".".$ext;
move_uploaded_file($_FILES["file"]["tmp_name"], "/uploads/".$filename);
}
// Solution 2: Using libraries
$uploader = new FileUploader();
$uploader->setAllowedTypes(["jpg", "png"])->setMaxSize("2MB");
Key Takeaways
Always validate file metadata before processing.