How can caching be implemented in PHP to improve performance when displaying images from a database?

Caching can be implemented in PHP to improve performance when displaying images from a database by storing the images in a temporary directory on the server. This way, the images can be served directly from the cache without needing to fetch them from the database every time a user requests them.

// Check if the image exists in the cache directory
$cacheDir = 'cache/';
$imageName = 'image.jpg';

if (file_exists($cacheDir . $imageName)) {
    // Serve the image from the cache
    header('Content-Type: image/jpeg');
    readfile($cacheDir . $imageName);
} else {
    // Fetch the image from the database
    $imageData = // Retrieve image data from the database

    // Save the image to the cache directory
    file_put_contents($cacheDir . $imageName, $imageData);

    // Serve the image
    header('Content-Type: image/jpeg');
    echo $imageData;
}