How can PHP developers ensure data validation and SQL injection prevention in file upload forms?
To ensure data validation and prevent SQL injection in file upload forms, PHP developers should sanitize user input by using prepared statements and parameterized queries when interacting with the database. Additionally, they should validate file uploads by checking file types, sizes, and ensuring proper file handling to prevent security vulnerabilities.
// Example of using prepared statements to prevent SQL injection
$stmt = $pdo->prepare("INSERT INTO files (file_name, file_size) VALUES (:file_name, :file_size)");
$stmt->bindParam(':file_name', $file_name);
$stmt->bindParam(':file_size', $file_size);
$stmt->execute();
// Example of validating file uploads
$allowed_types = array('jpg', 'jpeg', 'png', 'gif');
$max_size = 5242880; // 5MB
if (in_array(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION), $allowed_types) && $_FILES['file']['size'] <= $max_size) {
// Handle file upload
} else {
echo "Invalid file type or size.";
}