This is an archive of an inactive wiki and cannot be modified.

Caching with PHP

This technique gives a possible implementation for the CategoryBpCaching when using PHP. It focuses on implementing properly conditional HTTP GET, based on Last-Modification time.


Implementation Steps:

// $lastModifiedDate must be a GMT Unix Timestamp
// You can use gmmktime(...) to get such a timestamp
// getlastmod() also provides this kind of timestamp for the last
// modification date of the PHP file itself
function cacheHeaders($lastModifiedDate) {
  if ($lastModifiedDate) {
    if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $lastModifiedDate) {
      if (php_sapi_name()=='CGI') {
        Header("Status: 304 Not Modified");
      } else {
        Header("HTTP/1.0 304 Not Modified");
    } else {
      $gmtDate = gmdate("D, d M Y H:i:s \G\M\T",$lastModifiedDate);
      header('Last-Modified: '.$gmtDate);

// This function uses a static variable to track the most recent
// last modification time
function lastModificationTime($time=0) {
  static $last_mod ;
  if (!isset($last_mod) || $time > $last_mod) {
    $last_mod = $time ;
  return $last_mod ;


Detailed example

The following example details a usage of the code above with a MySQL database. It assumes the relevant table uses Mysql auto-timestamping mechanism in a column called 'last'.

// Connecting to the database
$dbh = mysql_connect("", "dbUser", 'l33t') ;

// In our select query, we include the timestamp of the last modification time
// converted to the UNIX timestamp format, since that's the format accepted by
// the functions defined above
$query = "SELECT id,name,UNIX_TIMESTAMP(last) FROM myTable WHERE login='foo'";
$res = mysql_db_query("myDb",$query,$dbh);
$row = mysql_fetch_array($res);

// We call the last-modification time tracker

// Before outputting any real content, we call the cacheHeaders() function

echo "Your name is ".$row[1];

Back to BestPracticesList


Contributions to this wiki are governed by the W3C policies for Contribution to W3C' wiki on Mobile Web.