Freelance Web Developer

Say Hi

Sep 17, 2011

Creating Cache Manifest File using PHP

HTML5 Application Cache provides a way to make your application work offline. Once your application resources got saved to browser cache, it remains cached until the manifest file is modified. ( Note that updating a file listed in the manifest doesn't mean the browser will re-cache that resource.) The manifest file itself must be changed.

For example you are using this manifest file :-


Changes in index.html or app.js will not force to re-cache. There must be few changes made in manifest file to update the cache.

If there are a lot of files and filders in your web application, manually listing them all in a manifest file would be a pain.
We have a simple solution of above problem. We can use PHP to list out all files and alter manifest file when any file got changed, so the cache can be updated.

How to use PHP code in .appcache file
We can use .php as menifest file but .appcache is the new recommended file extension for menifest file, and .manifest was the old one. So we are going to mimic file extensions and ll be running PHP code in the .appcache file. Its possible by adding this simple line to your .htaccess file :-

AddType application/x-httpd-php .appcache

The menifest file
We are going to write a little PHP code that reads the contents of the application directory (and its subdirectories) and creates the file list. Create a any.appcache file and put this code to it:-

  header('Content-Type: text/cache-manifest');
  echo "CACHE MANIFEST\n";

  $hashes = "";

  $dir = new RecursiveDirectoryIterator(".");
  foreach(new RecursiveIteratorIterator($dir) as $file) {
    if ($file->IsFile() &&
        $file != "./any.appcache" &&
        substr($file->getFilename(), 0, 1) != ".")
      echo $file . "\n";
      $hashes .= md5_file($file);
  echo "# Hash: " . md5($hashes) . "\n";

In this code the last last does a great trick, If anything from your list of files got changed, the line would be changes, and the browser file found that there is a need of cache update.

This trick was originally shared by the Jonathan Stark in his book "Building iPhone Apps with HTML, CSS, and JavaScript". I added some spices (using PHP code in .appcache file) and reshaped it.

Follow me on twitter.

Labels: , , ,

By :