What are the best practices for validating and sanitizing user input in PHP file upload forms?

When dealing with file uploads in PHP forms, it is crucial to validate and sanitize user input to prevent security vulnerabilities such as file injection attacks. To ensure the uploaded file is safe, always validate the file type, size, and content before processing it. Additionally, sanitize the file name to remove any special characters or potentially harmful code.

// Validate and sanitize file upload input
if(isset($_FILES['file'])){
    $file = $_FILES['file'];

    // Validate file type
    $allowed_types = array('jpg', 'jpeg', 'png', 'gif');
    $file_ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    if(!in_array($file_ext, $allowed_types)){
        die('Invalid file type. Allowed types: jpg, jpeg, png, gif');
    }

    // Validate file size
    if($file['size'] > 1048576){ // 1MB
        die('File size is too large. Maximum size allowed is 1MB');
    }

    // Sanitize file name
    $file_name = preg_replace("/[^A-Za-z0-9.]/", '', $file['name']);

    // Move uploaded file to desired directory
    move_uploaded_file($file['tmp_name'], 'uploads/' . $file_name);
}