What are some common file format validation pitfalls when uploading images in PHP?

One common file format validation pitfall when uploading images in PHP is not properly checking the file extension. Attackers can easily rename a malicious file to have a valid image extension like .jpg or .png. To mitigate this, it is important to validate the file's MIME type to ensure it is actually an image file.

// Check if the uploaded file is an image by validating its MIME type
$allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
$uploadedFileType = $_FILES['file']['type'];

if (!in_array($uploadedFileType, $allowedMimeTypes)) {
    // Invalid file type, handle error accordingly
    die('Invalid file type. Please upload a valid image file.');
}