What are best practices for validating file types before allowing them to be uploaded using PHP?

When allowing users to upload files to a website, it is important to validate the file type to prevent malicious files from being uploaded. One common approach is to check the file's MIME type using PHP before allowing it to be uploaded. This can help ensure that only files of certain types are accepted.

// Get the MIME type of the uploaded file
$mime = mime_content_type($_FILES['file']['tmp_name']);

// Allowed MIME types
$allowed_types = ['image/jpeg', 'image/png', 'image/gif'];

// Check if the MIME type is allowed
if (in_array($mime, $allowed_types)) {
    // File type is allowed, proceed with file upload
    move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
    echo 'File uploaded successfully.';
} else {
    // File type is not allowed
    echo 'Invalid file type. Please upload a JPEG, PNG, or GIF file.';
}