What are the common pitfalls to avoid when integrating file uploads with database insertions in PHP applications?
Common pitfalls to avoid when integrating file uploads with database insertions in PHP applications include not validating file types and sizes, not sanitizing user input to prevent SQL injection attacks, and not handling file upload errors properly. To solve these issues, always validate file types and sizes before uploading, sanitize user input before inserting it into the database, and handle file upload errors gracefully.
// Validate file type and size before uploading
$allowedTypes = ['image/jpeg', 'image/png'];
$maxSize = 5 * 1024 * 1024; // 5MB
if (!in_array($_FILES['file']['type'], $allowedTypes) || $_FILES['file']['size'] > $maxSize) {
echo "Invalid file type or size.";
exit;
}
// Sanitize user input before inserting into the database
$description = mysqli_real_escape_string($conn, $_POST['description']);
// Handle file upload errors
if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
echo "Error uploading file.";
exit;
}
// Perform database insertion
$sql = "INSERT INTO files (description, file_name) VALUES ('$description', '{$_FILES['file']['name']}')";
mysqli_query($conn, $sql);