Part of the EllisLab Network
x
 
Create New Page
 View Previous Changes    ( Last updated by Zacharias Knudsen )

Cache headers

When you set a header via $this->output->set_header(), but also use caching via $this->output->cache(), those headers you sent will not be cached along with your content.

This can be very problematic: if you’re caching CSS, for example, you want the cache to return that CSS along with the Content-Type header “text/css” - otherwise most browsers will interpret your CSS as just plain text, and hence not use it for rendering.

With a few simple alterations to the Output class, headers will also be cached and returned. This involved small changes to the _write_cache() and _display_cache() functions, shown below.

_write_cache function, around line 300 (surrounding code also shown)

// Implode all the headers into a newline-delimited string
// String is prepended with a pseudo-header giving the expiration time
$headers = "X-CI-Timestamp: " . (time() + ($this->cache_expiration * 60)) . "\n";
$headers .= implode("\n", $this->headers);

flock($fp, LOCK_EX);
fwrite($fp, $headers . "\n\n" . $output); // This line changed
flock($fp, LOCK_UN);
fclose($fp);
@
chmod($cache_path, DIR_WRITE_MODE);

_display_cache function, around line 360 (surrounding code also shown)

// Seperate headers and cache
list($headers, $cache) = explode("\n\n", $cache, 2);
        
// Get each header as an array item
$headers = explode("\n", $headers);
foreach (
$headers as $header)
{
    
// Is this header the timestamp pseudo-header?
    
if (FALSE === strpos($header, "X-CI-Timestamp: "))
    
{
        $this
->set_header($header); // No, it's not: set the header
    
}
    
else
    
{
        
// Has the file expired? If so we'll delete it.
        
$timestamp = substr($header, strlen("X-CI-Timestamp: "));
        if (
time() >= trim($timestamp))
        
{         
            
@unlink($filepath);
            
log_message('debug', "Cache file has expired. File deleted");
            return
FALSE;
        
}
    }
}

// Display the cache
$this->_display($cache); // This line changed

These additions automatically write headers into the cache and incorporate the timestamping in the same mechanism.

This code is given for demonstration; it could be cleaned up, by, for instance, adding a variable holding the timestamp pseudo-variable identifier, so that it needn’t be repeated, and one for the delimiters too.

We can now remove:

Lines 103 and 104

/*
* Note:  If a file is cached, headers will not be sent.  We need to figure out
* how to permit header data to be saved with the cache data...
*/


Category:Contributions -> Modifications