How can PHP be used to explicitly cache a page in order to improve loading times for images generated by a web application?

To improve loading times for images generated by a web application, we can explicitly cache the page using PHP. This involves setting appropriate caching headers to instruct the browser to cache the page for a specified amount of time. By doing so, the browser can store a local copy of the page and its resources, reducing the need to make repeated requests to the server.

<?php
// Set caching headers to cache the page for 1 hour
header("Cache-Control: max-age=3600");
header("Expires: " . gmdate("D, d M Y H:i:s", time() + 3600) . " GMT");

// Generate and output the image
$image = generate_image();
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>