One major problem faced by many dynamically generated websites is that of server load. Serving static HTML pages has a very light overhead for the server, but complex dynamically generated PHP pages can put some strain on the server, especially if many people are accessing the page at once.

The solution is caching (not cashing, as the picture implies): instead of regenerating the entire page every time, we serve up a saved copy that is updated at a given interval.

The first thing to do is to define a few key variables: an update interval and the file name for the cache file. Both of these can be completely arbitrary.

For the purposes of demonstration, we will use an update interval of 30 minutes, and name the cache file after the URI of the page.

<?php
	$interval = 30 * 60; // 30 minutes * 60 seconds per minute
	$filename = "cache/".basename(rtrim($_SERVER["REQUEST_URI"], '/')).".cache";
?>

Next, we need to check whether it’s time to perform an update. If it’s not, we serve up the contents of the cache file.

<?php
	$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.
	}

So the next step would be to regenerate and display the page if more time than the specified interval has passed.


<?php
	$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
?>
<!-- HTML goes here -->
<?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.
?>

This will allow you to take a lot of strain off of your server, and users will feel that your site loads faster.

Leave a Reply

Caching dynamic PHP webpages