Share

From this page you can share Making a Server Side Image Cache in PHP to a social bookmarking site or email a link to the page.
Social WebE-mail
Enter multiple addresses on separate lines or separate them with commas.
Making a Server Side Image Cache in PHP
(Your Name) has forwarded a page to you from Ajaxonomy
(Your Name) thought you would like to see this page from the Ajaxonomy web site.

Making a Server Side Image Cache in PHP

Tagged:  

Yesterday, I wrote about an application that I wrote called scovry and I mentioned that in writing the application I used a lot of caching. This included caching of images from an external thumbnail service server.

I thought that I would post the code that I am using to do this and quickly go over how it works. This code might be useful to any application that loads images from another server, to lessen the dependency on the other server. Below is the code that caches the images.

<?php
$imageurl =urldecode( $_GET['imageurl']);

$cachefile = 'caching_folder/'.urlencode($imageurl).'.jpg';
$cachetime = 604800;
// Serve from the cache if it is younger than $cachetime
if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) {
    header("Content-type: image/jpeg");
    readfile($cachefile);
    exit;
}
ob_start(); // Start the output buffer

$imginfo = getimagesize($imageurl);
header("Content-type: image/jpeg");
readfile($remoteImage);

// Cache the output to a file
$fp = fopen($cachefile, 'wb');
fwrite($fp, ob_get_contents());
fclose($fp);
ob_end_flush(); // Send the output to the browser
?>

The above code is used like an image proxy, but it adds the benefit of doing the image caching. So, the first thing to notice is that in my application the imageurl variable that is passed in through the url query string is an encoded url, so we decode it. This variable will hold the url encoded url of the image that we want to load. You may also notice that this code assumes that the image is a JPEG image, because that is what I was always going to be dealing with. So, if you use this code, you may need to add code to handle other image types.

The next import variable is the $cachetime as it sets how long (in seconds) the image will be cached before the cache is refreshed. The if statement checks if it should load the image on disk. The important part here is that it sets the document header content type to be an image and then loads the image using the readfile() method.

Now If the file does not exist or if it needs to be re-cached it loads the file from the server and writes it to the output buffer. Once again the document header content type is set to an image value and it gets the file via the readfile() method. In addition to this it writes the file to disk using the fopen() and fwrite() methods.

That is basically all there is to it. You can take a look at it in action by checking out scovry.