7.4. Thumbnail Caching

Dynamically generating thumbnails on the fly is certainly convenient, but you may find the album's performance somewhat lacking depending on the original size of an image, how many images are in an album and the load on the server. You may therefore want to put some form of caching in place. To keep everything simple and easy to update, I recommend making the modifications thumbnail.php.

Since all cached thumbnail images will be stored in one central cache directory, the inherent protection that comes from the album and image names being a unique combination is lost. The received file parameter may be run through sha1() to make sure valid thumbnail caches aren't overwritten.

The script should check to see if the thumbnail already exists within the cache directory and then its timestamp can be compared with that of the original image. If the thumbnail is newer than the original image then the thumbnail is still fresh and can be sent to the viewer instead of having to generate a new one for each request. However, if the thumbnail is older than the original image then it means someone updated the album and the thumbnail must be regenerated.

<?php // include shared code include '../lib/config.php'; // assumes CACHEDIR is defined alongside BASEDIR in config.php // make sure users only access files in the albums $file = (isset($_GET['file'])) ? (BASEDIR . '/' . $_GET['file']) : ''; if ($file && strpos(realpath($file), BASEDIR) === 0 && file_exists($file)) { // ...

Get PHP and MySQL®: Create-Modify-Reuse now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.