What best practices should be followed when handling file uploads and database inserts in PHP to ensure data integrity and security?

When handling file uploads and database inserts in PHP, it is important to validate and sanitize user input to prevent SQL injection and other security vulnerabilities. Additionally, file uploads should be checked for file type and size to prevent malicious uploads. Using prepared statements for database inserts can help prevent SQL injection attacks and ensure data integrity.

// Validate and sanitize file upload
$allowedFileTypes = ['jpg', 'jpeg', 'png'];
$maxFileSize = 5 * 1024 * 1024; // 5MB

if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $fileExtension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
    
    if (!in_array($fileExtension, $allowedFileTypes)) {
        die('Invalid file type.');
    }
    
    if ($_FILES['file']['size'] > $maxFileSize) {
        die('File size exceeds limit.');
    }
    
    // Process file upload
    move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}

// Use prepared statements for database inserts
$stmt = $pdo->prepare("INSERT INTO table_name (column1, column2) VALUES (:value1, :value2)");
$stmt->bindParam(':value1', $value1);
$stmt->bindParam(':value2', $value2);

// Sanitize user input before binding parameters
$value1 = filter_var($_POST['value1'], FILTER_SANITIZE_STRING);
$value2 = filter_var($_POST['value2'], FILTER_SANITIZE_STRING);

$stmt->execute();