What are some best practices for handling file uploads and permissions in PHP?

When handling file uploads in PHP, it is important to validate and sanitize user input to prevent security vulnerabilities such as file injection attacks. Additionally, setting appropriate file permissions on uploaded files can help protect sensitive data and prevent unauthorized access.

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

    // Validate file type
    $allowed_extensions = array('jpg', 'jpeg', 'png', 'gif');
    $file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
    if(!in_array($file_extension, $allowed_extensions)) {
        die('Invalid file type.');
    }

    // Sanitize file name
    $sanitized_file_name = filter_var($file_name, FILTER_SANITIZE_STRING);

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

// Set appropriate file permissions
$file_path = 'uploads/' . $sanitized_file_name;
chmod($file_path, 0644);