1. HTML Form Configuration for File Uploads
To transmit binary file payloads to the server, the HTML element must specify two attributes:
method="POST"enctype="multipart/form-data"
2. Inspecting the $_FILES Superglobal
When a file is submitted, PHP populates the $_FILES superglobal array with metadata:
'profile_pic.png', // Original filename on user computer
// 'type' => 'image/png', // MIME type reported by browser
// 'tmp_name' => '/tmp/phpYzdqkD', // Temporary file path on server
// 'error' => 0, // UPLOAD_ERR_OK code
// 'size' => 42100 // File size in bytes
// ]
3. Secure File Upload Implementation
$maxFileSize) {
die("File exceeds maximum allowed size (2MB).");
}
// 3. Validate file extension using whitelist
$allowedExtensions = ["jpg", "jpeg", "png", "pdf"];
$fileExtension = strtolower(pathinfo($file["name"], PATHINFO_EXTENSION));
if (!in_array($fileExtension, $allowedExtensions)) {
die("Invalid file format. Only JPG, PNG, and PDF files are allowed.");
}
// 4. Generate random safe filename to avoid overwriting or directory traversal attacks
$newFileName = bin2hex(random_bytes(16)) . "." . $fileExtension;
$uploadDirectory = __DIR__ . "/uploads/";
if (!is_dir($uploadDirectory)) {
mkdir($uploadDirectory, 0755, true);
}
$destination = $uploadDirectory . $newFileName;
// 5. Safely move uploaded file from temporary storage
if (move_uploaded_file($file["tmp_name"], $destination)) {
echo "File successfully uploaded as: " . htmlspecialchars($newFileName);
} else {
echo "Failed to save uploaded file.";
}
}