What are the potential security risks associated with using PHP to display images on a server?

Potential security risks associated with using PHP to display images on a server include the possibility of remote code execution, cross-site scripting (XSS) attacks, and directory traversal vulnerabilities. To mitigate these risks, it is important to validate user input, sanitize input data, and restrict access to sensitive directories.

<?php
// Validate and sanitize input data
$imagePath = filter_input(INPUT_GET, 'image', FILTER_SANITIZE_STRING);

// Restrict access to sensitive directories
$allowedDirectories = ['images/', 'uploads/'];
if (!in_array(dirname($imagePath) . '/', $allowedDirectories)) {
    die('Access denied');
}

// Display the image
header('Content-Type: image/jpeg');
readfile($imagePath);
?>