What are common errors when handling file uploads in PHP and how can they be avoided?
Common errors when handling file uploads in PHP include not checking for file size limits, not validating file types, and not securing the upload directory. These errors can be avoided by setting appropriate file size limits, validating file types using MIME types or file extensions, and ensuring the upload directory has proper permissions to prevent unauthorized access.
// Check file size limit
$maxFileSize = 2 * 1024 * 1024; // 2MB
if ($_FILES['file']['size'] > $maxFileSize) {
echo "File size exceeds limit.";
exit;
}
// Validate file type
$allowedFileTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($_FILES['file']['type'], $allowedFileTypes)) {
echo "Invalid file type.";
exit;
}
// Secure upload directory
$uploadDir = 'uploads/';
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0755, true);
}