What best practices should be followed when handling file uploads and database insertion in PHP?

When handling file uploads and database insertion in PHP, it is important to validate and sanitize user input to prevent security vulnerabilities such as SQL injection and file upload exploits. Use prepared statements to insert data into the database to prevent SQL injection attacks. Additionally, always validate file uploads by checking file types, size, and using secure file upload techniques.

// Validate file upload
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $file_name = $_FILES['file']['name'];
    $file_tmp = $_FILES['file']['tmp_name'];
    $file_size = $_FILES['file']['size'];
    $file_type = $_FILES['file']['type'];

    // Perform additional validation here

    // Move uploaded file to desired directory
    move_uploaded_file($file_tmp, 'uploads/' . $file_name);

    // Insert file details into database using prepared statement
    $stmt = $pdo->prepare("INSERT INTO files (name, size, type) VALUES (?, ?, ?)");
    $stmt->execute([$file_name, $file_size, $file_type]);
}