Hey all, I'm trying to cache a dynamically generated webpage by placing the html in a variable. What I can't figur out, is how to place the contents of this variable in a cache file that I can later retrieve and use when the page is loaded again. I would be really geat if someone here could nudge me in the right direction... Thanks
I'd something like this: 1> save the file with the same name as URL/$_SERVER[SCRIPT_NAME] (page.php?id=11) 2> Just on top of file (before html starts), add the timestamp, so you know when it was generated. 1111111111<html><head>... Now when page.php?id=11 is opened, quickly search if that cache exists. If it does, get file contents, and seperate the timestamp from it. See if timestamp is older than your expire time. (1 minute may be). If not, display content, else load new page, write to file again. $filetime= explode('<html', $contents); if( (time()-$filetime[0])>60 ){ //reload page; }else{ //show cache; }
You might find this thread interesting. Basiclly what I do is dump the HTML generated from my template class to a cache folder with file_put_contents then readfile() it to the browser. After that subsequent requests are handled by mod_rewrite without using PHP at all. I have a cron job setup that cleans pages older than 30 days out of the cache and the entire cache is dumped when navigatin elements change.
Hi and thank you very much for your reply. Here is what I have so far: <?php // Settings $cachedir = 'cache/'; // Directory to cache files in (keep outside web root) $cachetime = $MAX_TIME; // Seconds to cache files for $cacheext = 'txt'; // Extension to give cached files (usually cache, htm, txt) $cachefile = $cachedir . md5($url).".".$cacheext; // Cache file to either load or create if (file_exists($cachefile)) { $out = file_get_contents($cachefile); echo $out; }else{ fwrite ($cachefile, "$out"); echo $out; } ?> Code (markup): I'm just trying to create the file, check if it exists and read the contents if it does. Haven't gotten to the cache part yet. Problem is that the file doesnt exist, but the script seems to think it does... Can you identify any mistakes here? Thanks
fopen it first. also, your $out is not declared yet. try if this helps. untested. if (file_exists($cachefile)) { $out = file_get_contents($cachefile); echo $out; }else{ $fp = fopen ($cachefile,'w'); fwrite ($fp, "$timestamp_to_write"); fclose($fp); echo $timestamp_to_write; } PHP:
Well, it took some working out, but your help certainly got me some of the way. Needless to say, it now works brilliantly - so thank you very much!