What are best practices for implementing caching for generated images in PHP?
When generating images dynamically in PHP, it is important to implement caching to improve performance and reduce server load. One common approach is to store the generated images on the server and serve them directly if they already exist, instead of regenerating them every time a request is made.
// Check if the image already exists in the cache
$imagePath = 'cache/' . md5($imageName) . '.jpg';
if (file_exists($imagePath)) {
// Serve the cached image
header('Content-Type: image/jpeg');
readfile($imagePath);
} else {
// Generate the image
$image = imagecreatefromjpeg($imageName);
// Save the generated image to the cache
imagejpeg($image, $imagePath);
// Serve the generated image
header('Content-Type: image/jpeg');
imagejpeg($image);
// Clean up resources
imagedestroy($image);
}