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.
Pre-requisites:
- PHP 3 or superior
Implementation Steps:
- create a PHP include file with the following code
// $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"); } exit; } 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 ; }
- whenever you fetch information from a database, try to identify when that information was last modified, and call the function lastModificationTime() with the UNIX timestamp of the said time; (see detailed MySQL example example below)
add to each included file lastModificationTime(filemtime(__FILE__));; this ensures that whenever you modify a file included by the main script, the last modification date of the generated content gets updated accordingly
before sending any content to the browser (or when ever you want if you use Output buffering), call the cacheHeaders() function as follows:
cacheHeaders(lastModificationTime());
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'.
<?php // Connecting to the database $dbh = mysql_connect("db.example.org", "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 lastModificationTime($row[2]); // Before outputting any real content, we call the cacheHeaders() function cacheHeaders(lastModificationTime()); echo "Your name is ".$row[1]; ?>
Back to BestPracticesList