Are there any security concerns to consider when using $_GET parameters to display images in PHP?

Using $_GET parameters to display images in PHP can pose security concerns, such as allowing for directory traversal attacks or exposing sensitive information. To mitigate these risks, it is important to validate and sanitize the input received through $_GET before using it to load and display images. This can be done by checking if the input is a valid image file and restricting access to specific directories.

<?php
// Validate and sanitize the $_GET parameter
if(isset($_GET['image']) && preg_match("/^[a-zA-Z0-9]+\.(jpg|jpeg|png|gif)$/", $_GET['image'])) {
    $image = $_GET['image'];
    
    // Specify the directory where the images are stored
    $imageDirectory = 'images/';
    
    // Display the image
    echo '<img src="' . $imageDirectory . $image . '" alt="Image">';
} else {
    echo 'Invalid image parameter';
}
?>