A Simple Cache with PHP (2008-11-11)
ง่ายๆครับ ไม่ยากเลย ทำความเข้าใจได้ไม่ยาก
<?php
// start the output buffer
ob_start(); ?>
//Your usual PHP script and HTML here ...
<?php
$cachefile = "cache/home.html";
// open the cache file "cache/home.html" for writing
$fp = fopen($cachefile, 'w');
// save the contents of output buffer to the file
fwrite($fp, ob_get_contents());
// close the file
fclose($fp);
// Send the output to the browser
ob_end_flush();
?>
เพิ่มเติมอีกนิดตรวจสอบซะหน่อยว่ามันทำ Cache ไว้หรือยัง
<?php
$cachefile = "cache/home.html";
if (file_exists($cachefile)) {
// the page has been cached from an earlier request
// output the contents of the cache file
include($cachefile);
// exit the script, so that the rest isnt executed
exit;
}
?>
กำหนดอายุไขให้มันซะหน่อยมะ
<?php
// 5 minutes
$cachetime = 5 * 60;
// Serve from the cache if it is younger than $cachetime
if (file_exists($cachefile) &&
(time() - $cachetime < filemtime($cachefile)))
{
include($cachefile);
echo "<!-- From cache generated ".date('H:i',
filemtime($cachefile))."
-->\n";
exit;
}
?>
เป็นไงครับ ง่ายซะ อย่างงี้ก็หายเซ็งไปได้อีกนิด
|