如何先验证多文件再仅在合法时提交表单数据至MySQL数据库?
Fix: Only Insert Contact Info After Validating All Uploaded Files
Let's tackle this issue head-on. The core problem with your current code is that it inserts contact details into the database before checking if uploaded files are valid. We need to reverse that order: first validate all files, then run database operations only if everything checks out. We'll also fix the SQL injection risk (never directly plug user input into SQL queries!) and add robust error handling.
Step-by-Step Breakdown of Changes
- File validation first: We’ll check every uploaded file for errors and valid types upfront. If any file fails, we stop immediately and show an error.
- Database operations only post-validation: Once all files are confirmed valid, we insert contact info, then upload files and log them in the
imagestable. - Use prepared statements: This eliminates SQL injection, a critical security practice for handling user input.
- Transaction support: Ensures all database changes are rolled back if something goes wrong mid-process (e.g., a file upload fails after inserting contact info).
Modified Code
<?php if(isset($_POST['submit'])){ // Sanitize user input to clean up potentially unsafe content $obs_fname = filter_input(INPUT_POST, 'firstname', FILTER_SANITIZE_STRING); $obs_lname = filter_input(INPUT_POST, 'lastname', FILTER_SANITIZE_STRING); $obs_address = filter_input(INPUT_POST, 'adresse', FILTER_SANITIZE_STRING); // File upload configuration $targetDir = "uploads/"; $allowTypes = array('jpg','png','jpeg','gif'); $validFiles = []; $uploadError = false; $errorMessage = ""; // First: Validate all uploaded files if(isset($_FILES['files']) && !empty($_FILES['files']['name'][0])) { foreach($_FILES['files']['name'] as $key => $name) { // Check for upload errors (e.g., file too large, partial upload) if($_FILES['files']['error'][$key] !== UPLOAD_ERR_OK) { $errorMessage = "Error uploading file " . $name . ": Code " . $_FILES['files']['error'][$key]; $uploadError = true; break; } // Get and validate file extension $fileExt = strtolower(pathinfo($name, PATHINFO_EXTENSION)); if(!in_array($fileExt, $allowTypes)) { $errorMessage = "Invalid file type: " . $name . ". Allowed types: " . implode(', ', $allowTypes); $uploadError = true; break; } // Store valid file details for later processing $validFiles[] = [ 'name' => $name, 'tmp_name' => $_FILES['files']['tmp_name'][$key] ]; } } // Exit early if file validation fails if($uploadError) { echo $errorMessage; return false; } // Include database config only after validation passes include_once 'dbConfig.php'; try { // Start a transaction to ensure data consistency $db->begin_transaction(); // Insert contact information (only if files are valid) $stmt = $db->prepare("INSERT INTO bear (obs_fname, obs_lname, obs_address) VALUES (?, ?, ?)"); $stmt->bind_param("sss", $obs_fname, $obs_lname, $obs_address); if(!$stmt->execute()) { throw new Exception("ERROR SAVING CONTACT: " . $db->error); } $post_id = $db->insert_id; echo "Post id=".$post_id ."<br>\n"; // Upload valid files and log them in the database if(!empty($validFiles)) { // Create upload directory if it doesn't exist if(!is_dir($targetDir)) { mkdir($targetDir, 0755, true); } $stmt = $db->prepare("INSERT INTO images (eventID, file_name, uploaded_on) VALUES (?, ?, NOW())"); foreach($validFiles as $file) { $targetPath = $targetDir . basename($file['name']); // Move file to server directory if(!move_uploaded_file($file['tmp_name'], $targetPath)) { throw new Exception("Failed to upload file: " . $file['name']); } // Insert file record into database $stmt->bind_param("is", $post_id, $file['name']); if(!$stmt->execute()) { throw new Exception("ERROR INSERTING IMAGE: " . $db->error); } } } // Commit all changes if everything succeeded $db->commit(); header("Location: upload-complete.php"); exit; } catch(Exception $e) { // Roll back all database changes if any step failed $db->rollback(); echo $e->getMessage(); $db->close(); return false; } } ?>
Key Enhancements
- Early Validation: We catch invalid files before any database operations, preventing partial data from being saved.
- Transaction Safety: If a file upload fails after inserting contact info, we undo the contact insert to keep your database consistent.
- Security: Prepared statements and input sanitization eliminate SQL injection risks.
- Robust Error Handling: Clear, specific error messages help debug issues quickly.
- Directory Check: Automatically creates the uploads folder if it doesn’t exist, avoiding file save errors.
内容的提问来源于stack exchange,提问作者lunian
相关产品推荐
相关产品推荐

