"File is too large (exceeds PHP configured limits or form limit).", UPLOAD_ERR_PARTIAL => "File upload was interrupted.", UPLOAD_ERR_NO_FILE => "No file was uploaded.", UPLOAD_ERR_NO_TMP_DIR => "Missing a temporary folder for uploads.", UPLOAD_ERR_CANT_WRITE => "Failed to write file to disk.", UPLOAD_ERR_EXTENSION => "A PHP extension stopped the file upload.", default => "An unknown upload error occurred." }; die("Error: " . $error_message); } // 1. Validate file size if ($file['size'] > $max_file_size) { die("Error: File is too large. Max size allowed is " . ($max_file_size / 1024 / 1024) . "MB."); } // 2. Validate file extension $file_extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION)); if (!in_array($file_extension, $allowed_extensions)) { die("Error: Invalid file type. Allowed extensions are: " . implode(', ', $allowed_extensions)); } // 3. Validate MIME type (more robust than just extension) // Using finfo_open() is better for actual content type detection $finfo = finfo_open(FILEINFO_MIME_TYPE); $mime_type = finfo_file($finfo, $file['tmp_name']); finfo_close($finfo); if (!in_array($mime_type, $allowed_mime_types)) { die("Error: Disallowed MIME type detected: " . $mime_type); } // 4. Generate a unique and safe filename $safe_filename = bin2hex(random_bytes(16)) . '.' . $file_extension; $destination_path = $upload_directory . $safe_filename; // 5. Move the uploaded file if (move_uploaded_file($file['tmp_name'], $destination_path)) { echo "File uploaded successfully: $safe_filename"; // Optionally, perform further processing like image resizing, virus scanning etc. } else { die("Error: Failed to move uploaded file."); } } else { // Display file upload form echo '
'; echo 'Select file to upload: '; echo ''; echo '
'; } ?>