What are some potential pitfalls when using PHP to display images from a folder and how can they be avoided?

One potential pitfall when using PHP to display images from a folder is not properly sanitizing user input, which can lead to security vulnerabilities like directory traversal attacks. To avoid this, always validate and sanitize user input before using it to access files on the server.

<?php
// Validate and sanitize user input to avoid directory traversal attacks
$imageName = isset($_GET['image']) ? $_GET['image'] : '';
$imagePath = 'images/' . basename($imageName);

// Display the image
echo '<img src="' . $imagePath . '" alt="Image" />';
?>