How can PHP developers effectively cache generated images to optimize website performance?

To effectively cache generated images in PHP, developers can utilize browser caching and server-side caching mechanisms. By setting appropriate cache headers and storing generated images in a cache directory, the server can serve cached images instead of regenerating them for each request, improving website performance.

// Set cache control headers to enable browser caching
header("Cache-Control: max-age=3600, public");
header("Expires: " . gmdate('D, d M Y H:i:s', time() + 3600) . ' GMT');

// Check if cached image exists, if not generate and cache it
$cachedImagePath = 'cache/image.jpg';
if (file_exists($cachedImagePath)) {
    // Serve cached image
    header('Content-Type: image/jpeg');
    readfile($cachedImagePath);
} else {
    // Generate image
    $image = imagecreate(200, 200);
    $white = imagecolorallocate($image, 255, 255, 255);
    $black = imagecolorallocate($image, 0, 0, 0);
    imagestring($image, 4, 50, 50, 'Cached Image', $black);
    
    // Save generated image to cache
    imagejpeg($image, $cachedImagePath);
    
    // Serve generated image
    header('Content-Type: image/jpeg');
    imagejpeg($image);
    imagedestroy($image);
}