Page 1 of 1

HACK: Cache Pages for upto 2 hours

Posted: Thu 6. May 2004, 08:54
by girish
I don't know about you guys, but I got sick of the DB being hit on my fairly static page.

So I decided to make a quick hack to cache the pages for upto 2 hours, every 2 hours it'll rerun the page to generate a new page.

Here is the code.. all modifications are done on index.php (I use url_rewrite, but it should work without)


Step 1. Create a directory called "cache" in your main root folder of phpwcms, then chmod it to "777".

Step 2. At the start of index.php add (right before... require_once(...) calls):

Code: Select all

function calcElapsedTime($time)
{
        $diff = time()-$time;
        $diff = time()-$time;
        $daysDiff = floor($diff/60/60/24);
        $diff -= $daysDiff*60*60*24;
        $hrsDiff = floor($diff/60/60);
        return $hrsDiff;
}

// write to cache file
function cache($buffer){
        //write to cache file
        $fh = fopen('cache/'.$GLOBALS['page_name'], 'w+');
        fwrite($fh, $buffer);
        fclose($fh);
        // PHP_SELF
        //$buffer .= "writing to ".$GLOBALS['page_name'];
        return $buffer;
}

// figure out the name of the cache page
$page_name = "default";
if(count($_GET) > 0){
        if(strlen($_GET['id']) > 0) {
                $GLOBALS['page_name'] = $_GET['id'];
        } else {

                $getKeys = array_keys($_GET);
                //print ($getKeys[0]);
                $GLOBALS['page_name'] = $getKeys[0];
                if($GLOBALS['page_name'] == "")
                        $GLOBALS['page_name']  = "not_found";
        }
}

// figure out if cache is needed
//check if file exists
if(file_exists('cache/'.$page_name)){
$mfiletime = filemtime('cache/'.$page_name);


if(calcElapsedTime($mfiletime) < 2){
        // less than two hours
        // display old file
        $datafile = fopen('cache/'.$page_name,"r") or die ("File reading error");
        $Html = fread($datafile, 1000000);

        echo $Html;
        echo "Cache copy from: ".date("F j, Y, g:i a", $mfiletime);
        exit();
}
}

ob_start("cache");

On the bottom of the page (index.php), end it with...

Code: Select all

<?
ob_end_flush();

?>

Let me know if you guys have any problems, email me girish (a) patangay dot com

Caching ?

Posted: Thu 6. May 2004, 11:35
by Keules
Hi !

I changed my index.php and created the folder "cache".

I saw the index.php is already ending with "<?php ob_end_flush(); ?>"

Should i double this tag ? Now i insert your code on the top of my file after the comments of oliver.

Here my code of the index.php .

In the Cache Folder is no file, after visiting the index-page.

Please say me whats wrong in my code.

Thx
Keules

Code: Select all

<?php
/*************************************************************************************
   Copyright notice
   
   (c) 2002-2003 Oliver Georgi (oliver@phpwcms.de) // All rights reserved.
 
   This script is part of PHPWCMS. The PHPWCMS web content management system is
   free software; you can redistribute it and/or modify it under the terms of
   the GNU General Public License as published by the Free Software Foundation;
   either version 2 of the License, or (at your option) any later version.
  
   The GNU General Public License can be found at http://www.gnu.org/copyleft/gpl.html
   A copy is found in the textfile GPL.txt and important notices to the license 
   from the author is found in LICENSE.txt distributed with these scripts.
  
   This script is distributed in the hope that it will be useful, but WITHOUT ANY 
   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
   PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 
   This copyright notice MUST APPEAR in all copies of the script!
*************************************************************************************/


// this is for testing only
// returns how long this script is processed
// remove comments // to use this - look at the end of this
// page too

// require ("include/inc_ext/phpsniff/phpTimer.class.php");
// $timer =& new phpTimer();
// $timer->start('main');

// start session - neccessary if frontend users are available
// session_start();

###########################  page-caching for 2 hours ###########
################################################################################################

function calcElapsedTime($time) 
{ 
        $diff = time()-$time; 
        $diff = time()-$time; 
        $daysDiff = floor($diff/60/60/24); 
        $diff -= $daysDiff*60*60*24; 
        $hrsDiff = floor($diff/60/60); 
        return $hrsDiff; 
} 

// write to cache file 
function cache($buffer){ 
        //write to cache file 
        $fh = fopen('cache/'.$GLOBALS['page_name'], 'w+'); 
        fwrite($fh, $buffer); 
        fclose($fh); 
        // PHP_SELF 
        //$buffer .= "writing to ".$GLOBALS['page_name']; 
        return $buffer; 
} 

// figure out the name of the cache page 
$page_name = "default"; 
if(count($_GET) > 0){ 
        if(strlen($_GET['id']) > 0) { 
                $GLOBALS['page_name'] = $_GET['id']; 
        } else { 

                $getKeys = array_keys($_GET); 
                //print ($getKeys[0]); 
                $GLOBALS['page_name'] = $getKeys[0]; 
                if($GLOBALS['page_name'] == "") 
                        $GLOBALS['page_name']  = "not_found"; 
        } 
} 

// figure out if cache is needed 
//check if file exists 
if(file_exists('cache/'.$page_name)){ 
$mfiletime = filemtime('cache/'.$page_name); 


if(calcElapsedTime($mfiletime) < 2){ 
        // less than two hours 
        // display old file 
        $datafile = fopen('cache/'.$page_name,"r") or die ("File reading error"); 
        $Html = fread($datafile, 1000000); 

        echo $Html; 
        echo "Cache copy from: ".date("F j, Y, g:i a", $mfiletime); 
        exit(); 
} 
} 

ob_start("cache"); 


########################## end of page-caching ##############
################################################################################################


require_once ("include/inc_conf/conf.inc.php");
require_once ("include/inc_lib/default.inc.php");
require_once ("include/inc_conf/conf.template_default.inc.php");

##### WEBLOG ######
require_once ("version.inc.php");
##### / WEBLOG ######

require_once ("include/inc_lib/general.inc.php");
require_once ("include/inc_front/front.func.inc.php");
require_once ("include/inc_front/content.func.inc.php");

##### WEBLOG ######
require_once ("include/inc_ext/phpOpenTracker/phpOpenTracker.php");
phpOpenTracker::log();
##### / WEBLOG ######

//script chaching to allow header redirect
if($phpwcms["compress_page"]) {
	if(ini_get('zlib.output_compression')) { 
		ini_set( 'zlib.output_compression', '1' ); 
		ini_set( 'zlib.output_compression_level', $phpwcms["compress_page"] );
		ob_start();
	} else {
		ob_start("ob_gzhandler"); //with old style GZ Compression
	}
} else {
	ob_start(); //without Compression (or use browsers default)
}

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!--

phpwcms | open source web content management system

          developed by Oliver Georgi (http://www.webverbund.de)
          released under The GNU General Public License
          visit project page: http://www.phpwcms.de

          Release: <?php echo $phpwcms["version"]; ?>


//-->
<html>
<head>
<title><?php echo $content["pagetitle"] ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=<?php echo PHPWCMS_CHARSET ?>">
<?php echo $block["htmlhead"] ?>
<script src="<?php echo ".".$phpwcms["templates"] ?>inc_js/frontend.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="<?php echo ".".$phpwcms["templates"]."inc_css/".$block["css"] ?>">
</head>

<body<?php echo $content["body"] ?>>
<?php 

//  this regex's call the function 
if($phpwcms["rewrite_url"]) {
	$allowed_chars_in_url = "[".implode("]|[",array("@",",","\.","+","&","-","_","=","*","#","\/","%","?"))."]"; 
	$content["all"] = preg_replace("/(<a href=\"index.php?)(([a-z]|[A-Z]|[0-9]|".$allowed_chars_in_url.")*)(\")/e","url_search('\\2')",$content["all"]); 
	$content["all"] = preg_replace("/(onClick=\"location.href='index.php?)(([a-z]|[A-Z]|[0-9]|".$allowed_chars_in_url.")*)(\')/e","js_url_search('\\2')",$content["all"]); 
}
echo $content["all"];


// show how long it needs to create content
// remove comments // to use it
// $timer->stop('main');
// echo spacer(5)."<br /><span class=\"v09\">&nbsp;created in ".($timer->get_current('main'))." sec</span>";

?>
</body>
</html><?php
ob_end_flush();
?>

Posted: Fri 7. May 2004, 01:55
by girish
Nope, that should work.

One thing you might be missing is the chmod 777 command for your cache directory. That's why it's not writing.

Girish

Folder cache is on chmod 777

Posted: Fri 7. May 2004, 07:52
by Keules
Hi!

Nope, thats not right. I have set the folder on chmod 777. :?
There must be an failure in your script.

There are 2 functions who called ob_start(); , olivers ob_start(); and your ob_start("cache"); . But there is only one ob_end_flush();

Ciao
Keules

Posted: Sat 8. May 2004, 10:47
by jo
Hi girish,
I'm sorry, to tell you I tried to implement your script to index.php. It writes NOTHING to cache(777) directory. I'm on RH9 PHP Version 4.2.2.

Posted: Sat 8. May 2004, 11:05
by girish
jo wrote:Hi girish,
I'm sorry, to tell you I tried to implement your script to index.php. It writes NOTHING to cache(777) directory. I'm on RH9 PHP Version 4.2.2.
You know what, I might have an older version of phpwcms, I haven't really updated in a long time. I think maybe oliver put in cache pages code in there also.

Sorry for the confusion. :)

There should only be ONE ob_start, nested ob's are very ugly.

You might want to ask oliver what that output buffer code is for.