Poor man's cache...
| From: | Chris Hobbs | Date: | Thu, 27 Sep 2001 18:55:17 +0000 |
| Subject: | Poor man's cache... | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-69033@lists.php.net to get a copy of this message | ||
Well, I built a really awful Table of Contents script yesterday that has to grep through about a thousand files (Word docs, no less) to find the titles. Anyway, the script works great, but it is slow - 20-30 seconds per load, which is hardly acceptable. So, since the data will only change occasionally, I wrote the following wrapper for the script to check if a cachefile already exists, and if it does, it redirects to it. If not, it uses php's output buffering to build the page, writes the buffer out to the cache file, and then dumps the buffer to the browser.
When I change the docs on the site, I merely have to delete the cached file - the next person that loads it will rebuild it for me.
Anyway, I include it here for your edification.
<?
// Get just the script name, no /'s
ereg(".*/(.*)", $PHP_SELF, $regs);
$cachefilename = $regs[1].".html";
if (file_exists("/path/to/your/cache/$cachefilename")) {
header ("Location: $cachefilename");
exit ();
}
ob_start();
// All of your normal script goes here, complete with
// echo's, pure HTML between ?> and <?, whatever...
$complete_page=ob_get_contents();
$fd = fopen ("/path/to/your/cache/$cachefilename", "w");
fwrite ($fd, $complete_page);
fclose($fd);
ob_end_flush();
?>
Hope you find it useful!
--
_______ ___ _ ____ _____
Chris Hobbs / ____\ \ / / | | |/ ___\| __ \
Head Geek | (___ \ \ / /| | | | (___ | | | |
WebMaster \___ \ \ \/ / | | | |\___ \| | | |
PostMaster ____) | \ / | |__| |____) | |__| |
\____/ \/ \____/ \____/|_____/
http://www.silvervalley.k12.ca.us
chobbs@silvervalley.k12.ca.us