What best practices should be followed when using getimagesize() and displaying images in PHP?

When using getimagesize() to retrieve image dimensions in PHP, it is important to validate the image file before displaying it to prevent security vulnerabilities. One common best practice is to check the MIME type of the image file to ensure it is a valid image format. Additionally, always sanitize user input to prevent any malicious code execution.

// Example of validating image file before displaying it
$image = 'example.jpg';

// Get image size and MIME type
$image_info = getimagesize($image);
if ($image_info !== false) {
    $mime_type = $image_info['mime'];

    // Check if MIME type is a valid image format
    if ($mime_type == 'image/jpeg' || $mime_type == 'image/png' || $mime_type == 'image/gif') {
        // Display the image
        echo '<img src="' . $image . '" alt="Example Image">';
    } else {
        echo 'Invalid image format';
    }
} else {
    echo 'Error getting image information';
}