What are best practices for checking and displaying image file extensions in PHP?

When working with image files in PHP, it is important to verify the file extension to ensure that it is a valid image format. This can help prevent security vulnerabilities and ensure that only image files are processed. One way to do this is by checking the file extension against a list of allowed image extensions and displaying an error message if the extension is not valid.

// Define an array of allowed image extensions
$allowedExtensions = array('jpg', 'jpeg', 'png', 'gif');

// Get the file extension of the uploaded image
$extension = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);

// Check if the file extension is in the list of allowed extensions
if (!in_array($extension, $allowedExtensions)) {
    echo 'Invalid file extension. Please upload a JPG, JPEG, PNG, or GIF file.';
    // Additional code to handle the error, such as redirecting the user or displaying a form again
} else {
    // Process the image file
    // Additional code to handle the valid image file
}