What are the best practices for handling file uploads in PHP to ensure data integrity and prevent unauthorized access to server files?

When handling file uploads in PHP, it is crucial to validate and sanitize user input to prevent malicious attacks such as file injections. Additionally, it is important to store uploaded files in a secure directory outside the web root to prevent unauthorized access. Implementing proper file naming conventions and limiting file types can also enhance data integrity and security.

<?php
// Check if file was uploaded without errors
if(isset($_FILES['file']) && $_FILES['file']['error'] == 0){
    $uploadDir = '/path/to/secure/directory/';
    $uploadFile = $uploadDir . basename($_FILES['file']['name']);

    // Validate file type
    $allowedTypes = array('pdf', 'doc', 'docx');
    $fileType = pathinfo($uploadFile, PATHINFO_EXTENSION);
    if(!in_array($fileType, $allowedTypes)){
        die('Invalid file type. Only PDF, DOC, and DOCX files are allowed.');
    }

    // Move uploaded file to secure directory
    if(move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)){
        echo 'File uploaded successfully.';
    } else {
        echo 'Error uploading file.';
    }
} else {
    echo 'Error uploading file.';
}
?>