What potential pitfalls should be avoided when trying to display image files using PHP on a webpage?
One potential pitfall when displaying image files using PHP on a webpage is not properly sanitizing user input, which can lead to security vulnerabilities such as injection attacks. To avoid this, always validate and sanitize user input before using it to load or display image files.
// Example of sanitizing user input before displaying image file
$filename = $_GET['filename']; // assuming the filename is passed as a query parameter
$allowedExtensions = ['jpg', 'jpeg', 'png', 'gif']; // define allowed file extensions
// Validate file extension
$fileExtension = pathinfo($filename, PATHINFO_EXTENSION);
if (!in_array($fileExtension, $allowedExtensions)) {
die('Invalid file extension');
}
// Sanitize the filename to prevent directory traversal attacks
$cleanFilename = basename($filename);
// Display the image file
echo '<img src="images/' . $cleanFilename . '" alt="Image">';