What are some best practices for handling image display in PHP to ensure optimal performance?

To ensure optimal performance when displaying images in PHP, it is recommended to store images in a separate directory outside of the web root, use image caching techniques, and implement lazy loading for images to improve page load times.

// Example code snippet for displaying images in PHP with optimal performance

// Define the path to the directory where images are stored
$imageDirectory = '/path/to/image/directory/';

// Get the image file name from the URL parameter
$imageFileName = $_GET['image'];

// Validate the image file name to prevent directory traversal attacks
if (strpos($imageFileName, '..') === false) {
    // Output the image with proper headers
    header('Content-Type: image/jpeg');
    readfile($imageDirectory . $imageFileName);
} else {
    // Handle invalid image file names
    echo 'Invalid image file name.';
}