What are common pitfalls when handling file uploads in PHP forms?
Common pitfalls when handling file uploads in PHP forms include not checking for file size limits, not validating file types, and not securing the upload directory. To solve these issues, always set a maximum file size limit, validate file types using MIME types or file extensions, and move uploaded files to a secure directory outside of the web root.
// Set maximum file size limit to 5MB
$maxFileSize = 5 * 1024 * 1024;
// Validate file type before uploading
$allowedFileTypes = ['image/jpeg', 'image/png', 'image/gif'];
$uploadedFileType = $_FILES['file']['type'];
if (!in_array($uploadedFileType, $allowedFileTypes)) {
die('Invalid file type. Only JPEG, PNG, and GIF files are allowed.');
}
// Securely move uploaded file to a designated directory
$uploadDirectory = 'uploads/';
$uploadedFileName = $_FILES['file']['name'];
$uploadedFilePath = $uploadDirectory . $uploadedFileName;
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadedFilePath)) {
echo 'File uploaded successfully.';
} else {
echo 'Error uploading file.';
}