What are potential pitfalls when coding a PHP gallery to display images from a directory and how can they be avoided?

One potential pitfall when coding a PHP gallery to display images from a directory is not properly handling file paths, which can lead to errors or security vulnerabilities. To avoid this, always sanitize user input and use functions like realpath() to ensure the path is valid and safe.

// Example of sanitizing user input for file path in PHP gallery

$directory = $_GET['directory']; // Assuming user input for directory

// Sanitize user input for directory path
$directory = realpath('images/' . $directory);

// Check if directory is valid
if ($directory && is_dir($directory)) {
    // Display images from directory
    $images = glob($directory . '/*.{jpg,jpeg,png,gif}', GLOB_BRACE);
    foreach ($images as $image) {
        echo '<img src="' . $image . '" alt="Gallery Image">';
    }
} else {
    echo 'Invalid directory';
}