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);
}
Keywords
Related Questions
- How can the use of absolute paths for font files in PHP image generation scripts help prevent errors on different servers?
- What is the error message #1241 in PHP indicating in the context of the SQL query provided?
- What best practices should be followed when seeking support for PHP code in online forums?