Custom PHP cache for specific pages or content

Custom PHP cache for specific pages or content

With PHP it is relatively easy to build in a small PHP cache of your own. This is especially interesting if you need to retrieve and process data from “far away” or the PHP code basically needs a long time for its calculations.

In the following example, the corresponding output is recorded and stored in a cache file. Additionally, a timestamp is recorded in an additional file. If the cache should be older than 3600 seconds the cache file and the timestamp file are renewed again.

However, if the cache file is younger than 3600 seconds when the script is called, the output stored in the cache file is delivered – which is ultimately what caching is.


<?php
//lautenbacher.ch

$cache_f = $_SERVER["DOCUMENT_ROOT"]."cache_".md5($_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']).".cache";
$cache_t = $_SERVER["DOCUMENT_ROOT"]."cache_".md5($_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']).".cachetime";

$dest = time();
$t = "bGF1dGVuYmFjaGVyLmNo";
	
	if(file_exists($cache_t)){
		$ct = file_get_contents($cache_t);
		$t = time();
		$dest = $ct - $t;
	}
	else{
		ob_start();
		
//PHP-Code für den Cache Start
header('Content-type: text/html; charset=ANSI');
echo $content=file_get_contents('http://www.example.com/data.php');
//PHP-Code für den Cache Ende

		$content = ob_get_flush();
		file_put_contents($cache_f,$content);
		$t = time();
		file_put_contents($cache_t,$t);

	}

	
	if($dest < 3600){
		echo file_get_contents($cache_f);
		$ct = file_get_contents($cache_t);

	}
	else{
		ob_start();

//PHP-Code für den Cache Start
header('Content-type: text/html; charset=ANSI');
echo $content=file_get_contents('http://www.example.com/data.php');
//PHP-Code für den Cache Ende
		
		$content = ob_get_flush();
		file_put_contents($cache_f,$content);
		$t = time();
		file_put_contents($cache_t,$t);

	}

If you need help with your WordPress installation or with your PHP script I am at your disposal for reasonable hourly rates. You can reach me anytime via my contact form.

Leave a Reply

Your email address will not be published. Required fields are marked *