Phar: Browser caching for static files

Browsers are not able to cache static files delivered from PHP .phar archives, because Phar::webPhar() does not send out HTTP caching headers (Cache-Control, Expires).

The only way to intercept Phar::webPhar() before it delivers static CSS or JavaScript files is the $rewrites callback that may be passed as 5th parameter to webPhar().

A custom stub could look like this:

<?php
/**
 * Rewrite the HTTP request path to an internal file.
 * Adds expiration headers for CSS files.
 *
 * @param string $path Path from the browser, relative to the .phar
 *
 * @return string Internal path
 */
function rewritePath($path)
{
    if (substr($path, -4) == '.css') {
        header('Expires: ' . date('r', time() + 86400 * 7));
    }
    return $path;
}
 
Phar::webPhar(null, 'www/index.php', null, array(), 'rewritePath');
__HALT_COMPILER();
?>

Written by Christian Weiske.

Comments? Please send an e-mail.