What are the best practices for handling file uploads in PHP to ensure security and prevent unauthorized access?

When handling file uploads in PHP, it is important to validate and sanitize user input to prevent malicious attacks such as file injection or unauthorized access to sensitive files on the server. One way to ensure security is to restrict the file types that can be uploaded and store the files in a directory outside of the web root to prevent direct access. Additionally, using unique file names and implementing proper file permissions can further enhance security measures.

<?php
// Check if file was uploaded without errors
if(isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']['error'] == 0){
    $file_name = $_FILES['uploaded_file']['name'];
    $file_tmp = $_FILES['uploaded_file']['tmp_name'];
    
    // Validate file type
    $allowed_types = array('jpg', 'jpeg', 'png', 'gif');
    $file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
    
    if(in_array($file_extension, $allowed_types)){
        // Move file to secure directory
        $upload_dir = 'uploads/';
        $new_file_name = uniqid() . '.' . $file_extension;
        
        if(move_uploaded_file($file_tmp, $upload_dir . $new_file_name)){
            echo 'File uploaded successfully.';
        } else {
            echo 'Error uploading file.';
        }
    } else {
        echo 'Invalid file type.';
    }
} else {
    echo 'Error uploading file.';
}
?>