PHP: Caching generated images.

This is a quick tutorial on how to cache dynamically generated images in PHP. Personally, I love the results that you can get by using PHP’s GD and Image functions. However, dynamically generating images on the fly can be pretty resource intensive, especially if your website receives a sizeable amount of traffic.

In this example, I will generate a simple image using PHP and then save that image to the file system. The idea being that our script will generate the image on the first request, and then serve up the cached physical file for any requests that occur afterwards.

Let’s jump straight into the code:

Below is a drill-down / explanation of the code above:

  1. We set the location of our cached file.
  2. We check to see if the cached file exists by using PHP’s is_readable function. This function checks to see if a given file exists AND if it is readable by the web server.
  3. If the given $filepath is readable, we assume that a cached version of our image exists. In this case, we display the image by setting the content type to “image/jpeg” and by using the function readfile. In case you didn’t already know – readfile simply “reads a file and then writes it to the output buffer.” We then use the exit function to halt further execution of the script.
  4. If the given $filepath is not readable, we generate the image using PHP’s GD and Image functions. As you can see, the image in question is pretty simple. We’re merely outputting a white “Hello World” message onto a black background.
  5. After we’ve generated our image, we save the image to our given $filepath by using the imagejpeg function. The second parameter of this function is extremely important. If the second parameter is a filepath, then the function will save the image. If this parameter is set to NULL, then it will output the image directly. In our case, we save the image and then we ALSO output the image directly.

Hopefully, you found this tutorial to be useful!

Facebook Comments