What are the best practices for handling file operations in PHP when displaying images based on user input?

When displaying images based on user input in PHP, it is important to sanitize and validate the user input to prevent directory traversal attacks and other security vulnerabilities. It is recommended to store images in a separate directory outside of the web root and use a database to map user input to the corresponding image file.

// Sanitize and validate user input
$userInput = $_GET['image'];
$allowedImages = ['image1.jpg', 'image2.jpg', 'image3.jpg']; // List of allowed images

if (in_array($userInput, $allowedImages)) {
    // Directory where images are stored
    $imageDirectory = '/path/to/image/directory/';
    
    // Display the image
    echo '<img src="' . $imageDirectory . $userInput . '" alt="User Image">';
} else {
    echo 'Invalid image input';
}