Jump to content

Cache only part of a page


StefanRSA

Recommended Posts

Is it possible to cache only part of a page?

The header will carry the user session data and so more and the body of the page can be static.

 

If I use the following code everything is cahced and stuff around with user sessions.

	$interval = 30 * 60;
$filename = "cache/".basename( rtrim( $_SERVER["REQUEST_URI"], '/' ) ).".cache";

// serve from the cache if less than 30 minutes have passed since the file was created
if ( file_exists( $filename ) && (time() - $interval) < filemtime( $filename ) ) {
	readfile( $filename );
	exit(); // Terminate so we don't regenerate the page.
}

ob_start(); // This function saves all output to a buffer instead of outputting it directly.

// PHP page generation code goes here

The page detail:

<?php
// More page generation code goes here

$buff = ob_get_contents(); // Retrive the content from the buffer

// Write the content of the buffer to the cache file
$file = fopen( $filename, 'w" );
fwrite( $file, $buff );
fclose( $file );

ob_end_flush(); // Display the generated page.
?>

Link to comment
https://forums.phpfreaks.com/topic/202765-cache-only-part-of-a-page/
Share on other sites

<?php
class cache {
var $cache_dir = "cache/"; // Directory where the cache files will be stored
var $cache_time = 7320; // How much time will keep the cache files in seconds
var $caching = false;
var $cache_file = "";

// Constructor of the class
function cache() {

	$this->cache_file = $this->cache_dir . md5(urlencode($_SERVER["REQUEST_URI"]));

	if (file_exists($this->cache_file)) {

		//Grab the cache:
		$handle = fopen($this->cache_file, "r");
		do {
			$data = fread($handle, 8192);
			if (strlen($data) == 0) {
				break;
			}
			echo $data;
		} while (true);
		fclose($handle);
		echo "<span style='font-size:8px;'>cache page loaded</span>";
		exit();
	} else {
		//create cache :
		$this->caching = true;
		ob_start();
	}
}

   // You should have this at the end of each page
function close() {

	if ($this->caching) {
		// You were caching the contents so display them, and write the cache file
		$data = ob_get_clean();
		echo $data;
		$fp = fopen(str_replace("/ww.", "/", $this->cache_file), 'w');
		fwrite($fp, $data);
		fclose($fp);
	}
}
}
?>

 

<html>
<head>
</head>
<body>
<?php include("cache.class.php"); ?>
<?php $ch = new cache(); ?>
THIS CONTENT WILL BE CACHED
<?php $ch->close(); ?>
</body>
</html>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.