3 min read

Caching in PHP

Most web servers can handle a considerable amount of traffic, but why use caching in PHP? While Apache efficiently serves static files, dynamic scripts require additional processing power and memory. Caching reduces this overhead by storing processed content and serving it without repeated execution.

The Web is not just live visitors!

If your site has few visitors, the web server can manage requests efficiently. However, automated bots can slow down or even crash your site, affecting other websites on the same server.

WordPress Super Cache - must-have plugin

Even if your blog has low traffic, you should install the WordPress Super Cache plugin. WordPress generates multiple database queries for each page request, consuming server resources. With Super Cache, pages are stored as static files, reducing database usage and improving performance.

Caching functions for PHP Sites

There are several ways to implement caching, from server modules to PHP-based solutions. The best approach depends on your hosting environment and application requirements.

eAccelerator project

If you have root access to your server, consider using eAccelerator, a PHP extension that caches compiled scripts. I have tested it on multiple servers, and it significantly improves performance.

PHP-based caching

To cache individual pages, consider the following approach. This script saves generated content as static HTML files and serves them when needed.

// Function to fetch and write data to a file.
function getAndWrite($url, $cacheFile) {
  $string = file_get_contents($url);
	$f = fopen($cache_file, 'w');
	fwrite ($f, $string, strlen($string));
	fclose($f);
	return $string;
}

// Function to read cached content.
function readContent($path) {
  $f = fopen($path, 'r');
	$buffer = '';
	while(!feof($f)) {
		$buffer .= fread($f, 2048);
	}
	fclose($f);
	return $buffer;
}

$cacheFile = '/home/user/public_html/cache/cache.page.php';
$url = 'http:s//www.domain.com/page.php';

if (file_exists($cacheFile)) {
  // When cache file was created.
  $timeDiff = time() - filemtime($cacheFile);
  // Use cache if it's less than a day old.
  if ($timeDiff < 3600 * 24) { 
    // Get file.
    $html = readContent($cacheFile);
  } else {
    // Create a new file if do not exist.
    $html = getAndWrite($url, $cacheFile);
  }
}else {
  // Create a new file if do not exist.
  $html = getAndWrite($url, $cacheFile);
}

echo $html;
exit;

While simple, this method is not dynamic. To implement caching efficiently, maintain a list of cache files and URLs.

URL Rewriting for cached pages

In this case, we use part of the URL and pass this string as a variable through the request. Here are a few example URLs:

http://domain.com/page/ajax-tutorial
http://domain.com/page/php-parsing
http://domain.com/page/jquery-plugin

Use mod_rewrite in .htaccess to structure URLs for caching:

RewriteEngine on
RewriteRule ^page/([a-z\-]*)$ /page.php?pageurl=$1 [L]

Modify page.php to generate cached pages automatically:

if (!empty($_GET['pageurl']) && preg_match('/^[a-z\-]*$/', $_GET['pageurl'])) {
  $cacheFile = '/home/user/public_html/cache/cache-' . $_GET['pageurl'] . '.php';
  $url = 'https://www.domain.com/page.php?page=' . $_GET['pageurl'];
} else {
  header("HTTP/1.1 301 Moved Permanently");
  header("Location: " . $url);
  exit;
}

This approach improves website performance and handles high traffic efficiently.

P.S. The code provided is an example and should be adjusted based on your specific setup.