6

Title says it all, we do not have control over our server environment and although we can request for them to recompile apache for us it will not happen overnight.

Is there anything we can do is these modules (mod_expires, mod_headers) are not available to help with specifying certain content (images, js, css) should be cached or are we out of luck ?

1 Answer 1

6

One option is to send them through a PHP script and have that script out caching headers for you. It accomplishes the same thing with only a little extra overhead for having to have PHP serve the image as a proxy.

Example:

HTML:
<img src="/images/img.php?img=someimage.png">

PHP:
<?php
    $filename = $_GET['img'];
    $file = '/path/to/file/' . $filename;

    // Do verification that the file exists, they're not after any secure 
    // files, etc. Not shown here   

    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename=' . basename($file));
    header('Content-Transfer-Encoding: binary');
    header("Last-Modified: " . date( "D, j M Y H:i:s", strtotime("- 1 month")));
    header("Expires: Thu, 20 Sep 2012 05:00:00 GMT");
    header("Cache-Control: max-age=2692000, public"); 
    header("Pragma: cache"); 
    ob_clean();
    flush();
    readfile($file);
    exit;

?>
5
  • Interesting answer. I need to talk with system admin to determine if its worth the time to implement. Thanks!
    – Chris
    Commented Sep 24, 2010 at 14:46
  • Do you see any potential security problems with this? Perhaps I should have up there an array of filenames that I use and ignore any other requests to this page?
    – Chris
    Commented Sep 24, 2010 at 15:57
  • 1
    That's a good idea. Also make sure the file exists (file_exists()) and make sure the path is in your web root and not in /etc or something like that. You can also make sure the file extension is one you support (.png, .js, etc) and not something else like .exe.
    – John Conde
    Commented Sep 24, 2010 at 16:13
  • I had the same idea. But how would this affect performance? Any experiments or numbers to point to?
    – Daniel
    Commented May 3, 2013 at 13:53
  • It's really fast. Unless you're very high volume performance shouldn't even be a concern.
    – John Conde
    Commented May 3, 2013 at 13:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.