How can PHP scripts be modified to securely access and display images from local directories without compromising security?
When accessing and displaying images from local directories in PHP scripts, it is important to sanitize user input to prevent directory traversal attacks. One way to securely access and display images is to use a whitelist approach, where only images from specific directories are allowed to be displayed. By validating the image path against a predefined list of directories, we can prevent malicious users from accessing sensitive files on the server.
<?php
$allowedDirectories = ['images/', 'uploads/']; // Define allowed directories
$imagePath = $_GET['image']; // Get image path from user input
foreach ($allowedDirectories as $directory) {
if (strpos($imagePath, $directory) === 0) {
$imagePath = $directory . basename($imagePath); // Sanitize image path
break;
}
}
echo '<img src="' . $imagePath . '" alt="Image">';
?>