利用etag来实现php等动态页面的cache
现在web2.0难的就是对cache的实现,下面是小弟的一点漏见:
这里以php为例,因为小弟只会耍一点PHP ![]()
先来看看什么是Etag?
Etag(Entity tags )实体标签。这个tag和你在网上经常看到的标签云那种tag有点区别。这个Etag不是给用户用的,而是给浏览器缓存用的。Etag是服务器告诉浏览器缓存,缓存中的内容是否已经发生变化的一种机制。通过Etag,浏览器就可以知道现在的缓存中的内容是不是最新的,需不需要重新从服务器上重新下载。这和 “Last-Modified”的概念有点类似。
下面我们就可以利用“Output Control 输出控制函数”来灵活控制了,程序代码片如下:
name: cgi_buffer.php
[php]
< ?php
/*
(c) 2000 Copyright Mark Nottingham
This software may be freely distributed, modified and used,
provided that this copyright notice remain intact.
This software is provided 'as is' without warranty of any kind.
cgi_buffer is a library that may be used to improve performance of CGI
scripts in some circumstances, by applying HTTP mechanisms that are typically
not supported by them.
THIS LIBRARY REQUIRES PHP 4.01 OR GREATER
For more information:
http://www.mnot.net/cgi_buffer/
Many thanks to Chuck Hagenbuch.
*/
$version = "0.3";
$send_body = true;
$body = ob_get_contents();
ob_end_clean();
if (! isset($generate_etag)) {
$generate_etag = true;
}
if (! isset($compress_content)) {
$compress_content = true;
}
if ($compress_content && extension_loaded('zlib')) {
$ae = split(',', str_replace(' ', '', getenv('HTTP_ACCEPT_ENCODING')));
$enc = false;
if (in_array('gzip', $ae)) {
$enc = 'gzip';
} else if (in_array('x-gzip', $ae)) {
$enc = 'x-gzip';
}
if ($enc) {
$body = gzEncode($body);
header('Content-Encoding: ' . $enc);
header('Vary: Accept-Encoding');
}
}
if ($generate_etag) {
$etag = '"' . md5($body) . '"';
header ("ETag: " . $etag );
$inm = split(',', getenv("HTTP_IF_NONE_MATCH"));
foreach ($inm as $i) {
if (trim($i) == $etag) {
header ("HTTP/1.0 304 Not Modified");
$send_body = false;
break;
}
}
}
if ($send_body) {
header ("Content-Length: " . strlen($body));
print $body;
}
function gzEncode($content) {
/*
* Gzip encide data, generating a valid gzip header and footer.
* Author: Chuck Hagenbuch
*/
$page = "\x1f\x8b\x08\x00\x00\x00\x00\x00";
$size = strlen($content);
$crc = crc32($content);
$content = gzcompress($content, 2);
$page .= substr($content, 0, strlen($content) - 4);
for ($i = 0; $i < 4; $i++) {
$page .= chr($crc % 256);
$crc = floor($crc / 256);
}
for ($i = 0; $i < 4; $i++) {
$page .= chr($size % 256);
$size = floor($size / 256);
}
return $page;
}
?>
[/php]
例子程序:ex.php
[php]
< ?php
$version = "0.3";
ob_start();
ob_implicit_flush(0);
?>
< ?php
print "I'm bixuan";
?>
sex
ex.php
< ?php
require('cgi_buffer.php');
?>
[/php]
其实多的就不说了,当页面内容没变的话,那么etag也没变,那么浏览器就会将页面cache下来,而程序上只要返回http 304即可!
如果结合php的文件cache那会更好!cgi_buffer.php里还加上了压缩,关于压缩的使用,其实也是仁者见仁,智者见智,关键是适合自己用!
小弟写点小文语无伦次,望见谅,同时还请朋友多指教!

myz 21:42 on 2008 年 05 月 21 日 链接地址
不错的文章