How can PHP developers improve error handling and user feedback when encountering issues with file uploads, such as displaying custom error messages based on MIME types or file formats?

When encountering issues with file uploads, PHP developers can improve error handling and user feedback by checking the MIME type or file format of the uploaded file and displaying custom error messages accordingly. This can help prevent users from uploading potentially harmful files and provide clear guidance on the expected file types.

// Check the MIME type of the uploaded file
$allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
$uploadedFileType = $_FILES['file']['type'];

if (!in_array($uploadedFileType, $allowedMimeTypes)) {
    $errorMessage = 'Invalid file format. Please upload a JPEG, PNG, or GIF file.';
    // Display the custom error message to the user
    echo $errorMessage;
} else {
    // Process the file upload
}