What are the best practices for validating image types and sizes in PHP when implementing an image upload feature?

When implementing an image upload feature in PHP, it is important to validate the image types and sizes to ensure security and prevent any potential issues with the uploaded files. This can be done by checking the file type using functions like `exif_imagetype()` or `getimagesize()`, and verifying the file size against a predefined limit. By implementing these checks, you can ensure that only valid image files are accepted and that they do not exceed a certain size limit.

// Validate image type
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
$imageType = exif_imagetype($_FILES['image']['tmp_name']);

if (!in_array(image_type_to_mime_type($imageType), $allowedTypes)) {
    echo "Invalid image type. Please upload a JPEG, PNG, or GIF file.";
    exit;
}

// Validate image size
$maxSize = 2 * 1024 * 1024; // 2MB
if ($_FILES['image']['size'] > $maxSize) {
    echo "Image file is too large. Please upload an image that is less than 2MB.";
    exit;
}

// If both checks pass, proceed with uploading the image
// Your image upload code here