Interview question
How do you securely handle file uploads in PHP? PHP में file uploads को securely कैसे handle करें?
Answer
Unrestricted file uploads can let attackers upload executable scripts disguised as images. Multiple layers of validation are needed.
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
$maxSize = 2 * 1024 * 1024; // 2MB
$fileInfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($fileInfo, $_FILES['upload']['tmp_name']);
if (!in_array($mimeType, $allowedTypes)) {
die('Invalid file type');
}
if ($_FILES['upload']['size'] > $maxSize) {
die('File too large');
}
$newName = bin2hex(random_bytes(16)) . '.jpg';
move_uploaded_file($_FILES['upload']['tmp_name'], '/uploads/' . $newName);| Practice | Why |
|---|---|
| Check actual MIME type, not extension | Extensions can be spoofed easily |
| Rename uploaded files | Prevents overwriting and path traversal |
| Store outside webroot or block execution | Even if malicious, script can't run |
Unrestricted file uploads attackers को executable scripts को image जैसा दिखाकर upload करने देते हैं। कई layers की validation चाहिए।
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
$maxSize = 2 * 1024 * 1024;
$fileInfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($fileInfo, $_FILES['upload']['tmp_name']);
if (!in_array($mimeType, $allowedTypes)) {
die('Invalid file type');
}
$newName = bin2hex(random_bytes(16)) . '.jpg';
move_uploaded_file($_FILES['upload']['tmp_name'], '/uploads/' . $newName);Was this answer clear?