How to Leverage Browser Caching without using .htaccess

When it comes to improving the speed of your website (and your Google Page Speed score), one of the most important things to do is to leverage browser caching.

Usually, this would be done with .htaccess, using the mod_expires or mod_headers modules. Unfortunately, some shared hosts don't have any of these modules installed, or forbid the use of .htaccess altogether. We've had this problem with Informatics-Tech. Our provider, Awardspace, did not have the mod_expires or mod_headers modules available. Still, being really satisfied with Awardspace, we wanted to stick with them... so we set off for a solution, and we found one!



Note: Unfortunately, this method only works with image files. This still helps enormously since images generally represent the largest files of a typical webpage.

Using a PHP Script to Serve the images

The title says it all, instead of using .htaccess to specify cache information, we use a PHP script to serve the images on the page. There is a little overhead to having the script do all the work, but it's negligible. Using this script does mean that you will have to change the HTML that links to your images.

Setting it all up

Ok, so first of all, you'll need the actual PHP script. Keep in mind that this is the script in its simplest form, and doesn't check to make sure the file exists, nor provide any other form of security.


$filename = $_GET['img'];
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($filename));
header('Content-Transfer-Encoding: binary');
header("Expires: Sat, 20 Oct 2015 00:00:00 GMT");
header("Cache-Control: max-age=2692000, public");
header("Pragma: cache");




Right-click the button above and select save as to download...


The script is quite simple; it takes an image as argument, and then specifies the correct header information for that image, such as the expiry date and the maximum age. To actually USE it, you'll need to download img.php (see the button above) and place it in the same directory as your images, as such:


Img.php in it's correct folder


Now, you need to edit your HTML and CSS code. Currently, you probably refer to images by typing something like <img src="images/an-image.jpg"/>. This will still work, but won't leverage browser caching. Instead, you'll need to use <img src="images/img.php?img=an-image.jpg"/>, and same goes for CSS.


That's basically it! Now, Google Page Speed should acknowledge the change, thus improving your score. For us at Informatics-Tech, this method actually gave us about a 12 point gain! There are some drawbacks though, like the clunky HTML and the fact that this only works with images, but it's still better that nothing.