This post originated from an RSS feed registered with PHP Buzz
by Stephan Schmidt.
Original Post: 1d New PEAR proposal: HTTP_Cache 13
Feed Title: a programmer's best friend
Feed URL: http://blog.php-tools.net/rss.php?version=1.0
Feed Description: The blog of PHP Application Tools
eca
I just proposed a new package for inclusion in PEAR: HTTP_Cache. This package helps you creating ConditionalGet requests in your pages. This helps you keep the traffic low on your sites as it only sends the request body with the first request and a 304 (Not Modifed) header on subsequent requests. This is especially useful, if a page that is requested quite often is not changed a lot, but still is generated by PHP, so the browser will not cache it by default.
If you would like to implement this in your site, HTTP_Cache does all the work for you and even is able to work with output buffering. If using this feature, you only need to add two lines of code to the scripts you want to cache: <?php
require_once 'HTTP/Cache.php';
$cache = &new HTTP_Cache(array('auto' => true));
echo "You now may send any data to the browser";
?>
HTTP_Cache will generate a unique id for the current browser and send the following headers: Cache-Control: must-revalidate
Etag: e33b111743ff17c7829cd6bdad6815cb
On the next request the client will resend the ETag back to the server and HTTP_Cache will compare the client's ETag with the one that will be generated on the server. If both tags match, the data will not be send to the client, but a 304 header will be issued: HTTP/1.x 304 Not Modified
The only drawback is that HTTP_Cache will need to create an MD5-sum of the content, which could slow your application down in some cases. But using the cache will speed up your site as your webserver does not have to send as much data as without the HTTP_Cache.
Furthermore you may supply the unique id so HTTP_Cache does not need to create use the md5() function. This is especially helpful, when you are already using a serverside cache system and already generated a unique cache key for the current page. In this case you may also check whether the browsercache is valid so you do not need to load the cache file from disk: <?php
require_once 'HTTP/Cache.php';
$cache = &new HTTP_Cache();
// create an etag
$etag = 'hfhfhjfjddhfhjdshdddkjd33';
$cache->setEtag($etag);
// The browser cache is not valid
if (!$cache->isValid()) {
// create your content
$html = 'Do some expensive HTM creation....';
// pass it to the cache
$cache->setBody($html);
}
// send header or data
$result = $cache->send();
?>
If you are interested in this package, take a look at the package proposal or download the first version from out site.
17