What are the potential security risks of allowing direct access to image files on a web server?

Allowing direct access to image files on a web server can pose security risks such as unauthorized users being able to view sensitive information, potential exploitation of vulnerabilities in image processing libraries, and increased risk of hotlinking. To mitigate these risks, it is recommended to store images outside of the web root directory and use PHP to serve images to users through controlled access.

<?php
// Prevent direct access to image files
if(isset($_GET['image'])) {
    $image = $_GET['image'];
    
    // Validate image file path
    $imagePath = '/path/to/images/' . $image;
    
    // Check if file exists and is within allowed directory
    if(file_exists($imagePath) && strpos(realpath($imagePath), '/path/to/images/') !== false) {
        // Output image with appropriate headers
        header('Content-Type: image/jpeg');
        readfile($imagePath);
        exit;
    } else {
        // Handle error or redirect to a default image
        header('Location: /path/to/default/image.jpg');
        exit;
    }
}
?>