質問

Is it possible to generate a html5 cache manifest dynamically? I've tried php (following this tutorial among others http://grinninggecko.com/dynamic-cache-manifest/ ) with no success at all.

役に立ちましたか?

解決

Quite sure, but let me tell you: getting HTML5 Offline content to work nicely with JavaScript applicationCache.update() et. al. is somewhat messy if you're new to it. In the end everything works as... documented! But CAVEAT LECTOR...

Anyway, here is a (hopefully) self-explaining PHP-only example, for which you'll need an .htaccess file. This will tell your server to interpret the cache.manifest as PHP code (needed since there is no .php extension).

Your .htaccss file in case you use a FCGI Wrapper:

AddType text/cache-manifest .manifest

<FilesMatch "\.(manifest)$">
  SetHandler fcgid-script
  FcgidWrapper /folder/to/your/php-fcgi-starter .manifest
  Options +ExecCGI
</FilesMatch>

Your .htaccess file in case you use the apache php module (most of the time, that will be the default case):

AddType text/cache-manifest .manifest

<FilesMatch "\.(manifest)$">
    SetHandler application/x-httpd-php
</FilesMatch>

Your cache.manifest file:

<?php

// only cache files in the following folders (avoids other stuff like "app/")
$folders = array('js', 'lib', 'views', 'styles');
$files = array('index.html');

// recursive function
function append_filelist(&$files, $folder) {
  if ($dh = opendir($folder)) {
    while (($file = readdir($dh)) !== false) {
      if ( ! in_array($file, array('.', '..', '.svn')) &&
             (substr($file, -4) != ".swp")) {
        if (is_dir($folder."/".$file))
          append_filelist($files, $folder."/".$file);
        else
          //$files[] = $folder."/".$file."?hash=".md5_file($folder."/".$file);
          $files[] = $folder."/".$file;
      } // if
    } // while
  } // if
}

// init
foreach ($folders as $folder)
  if (is_dir($folder))
    append_filelist($files, $folder);

// generate output
$body = "CACHE MANIFEST\n\nCACHE:\n";
foreach ($files as $file)
  $body .= $file."\n";
$body .= "\nNETWORK:\n*\n";

// render output (the 'Content-length' header avoids the automatic creation of a 'Transfer-Encoding: chunked' header)
header('Content-type: text/cache-manifest');
header('Content-length: '.strlen($body));
echo $body;

Good luck!

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top