What best practices should be followed when displaying images in a PHP script?
When displaying images in a PHP script, it is important to ensure that the images are not directly accessible by users and to prevent any security vulnerabilities such as directory traversal attacks. One common best practice is to store images outside of the web root directory and use PHP to fetch and display them securely.
<?php
// Define the path to the image directory
$imageDir = '/path/to/image/directory/';
// Get the image file name from a query parameter
$imageName = $_GET['image'];
// Validate the image file name to prevent directory traversal
if (strpos($imageName, '..') === false) {
// Display the image if it exists in the image directory
$imagePath = $imageDir . $imageName;
if (file_exists($imagePath)) {
header('Content-Type: image/jpeg'); // Set the appropriate content type
readfile($imagePath); // Output the image
exit;
}
}
// Display a default image or an error message if the image is not found
echo 'Image not found';
?>