Skip to content
PHP Logo

What are some potential issues with dynamically displaying images from different directories on a web server in PHP?

One potential issue with dynamically displaying images from different directories on a web server in PHP is that it can expose sensitive information about the server's directory structure if not properly sanitized. To solve this issue, you can use a whitelist approach where you only allow specific directories to be accessed.

php
<?php

// Define an array of allowed directories
$allowedDirectories = ['images', 'photos'];

// Get the directory from the user input
$userDirectory = $_GET['directory'];

// Check if the user directory is in the allowed directories array
if (in_array($userDirectory, $allowedDirectories)) {
    // Display the image from the specified directory
    echo '<img src="/path/to/' . $userDirectory . '/image.jpg" alt="Image">';
} else {
    // Display an error message
    echo 'Invalid directory specified.';
}

?>