Are there any best practices for handling file uploads and database insertions in PHP?

When handling file uploads and database insertions in PHP, it is important to validate and sanitize the uploaded files to prevent security vulnerabilities such as SQL injection and file injection attacks. It is also crucial to move the uploaded files to a secure directory on the server and store the file path in the database to maintain data integrity.

// Handle file upload
$uploadDir = 'uploads/';
$uploadFile = $uploadDir . basename($_FILES['file']['name']);

if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
    // File uploaded successfully, now insert into database
    $filePath = $uploadFile;

    // Perform database insertion
    $conn = new mysqli($servername, $username, $password, $dbname);
    $sql = "INSERT INTO files (file_path) VALUES ('$filePath')";
    
    if ($conn->query($sql) === TRUE) {
        echo "File uploaded and inserted into database successfully.";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
    
    $conn->close();
} else {
    echo "Error uploading file.";
}