What are some best practices for retrieving and displaying images in a PHP application while maintaining performance and security?

When retrieving and displaying images in a PHP application, it is important to optimize performance and ensure security. One way to achieve this is by storing images in a separate directory outside of the web root to prevent direct access. Then, use PHP to retrieve and display the images through controlled access, such as using image resizing techniques to prevent large file sizes from affecting performance.

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

// Retrieve image filename from database or input
$imageFilename = 'example.jpg';

// Check if the image file exists
if (file_exists($imageDirectory . $imageFilename)) {
    // Display the image with proper headers
    header('Content-Type: image/jpeg');
    readfile($imageDirectory . $imageFilename);
} else {
    // Display a placeholder image or error message
    echo 'Image not found';
}
?>