2010
05.06

When having to implement static binaries on web sites (like images, flash etc) sometimes browser caching can be a real headache. Particularly the Flash player doesn’t seem to care too much about headers and no-cache metas, so when I had a .swf that simply refused to reload a while back I came up with the below workaround. It utilizes the fact that PHP is somewhat binary safe, and pads the binary with NULL characters of random amounts in order to force reloads. The method is not in any way limited to this use but can be applied to any situation when caching of binaries is a big no-no.

For those of you who doesn’t really understand the code, here’s how to use it:

  1. Create a PHP file in the same directory as your binary swf-file. Give it the same name, only with the .php extension (ie. for movie.swf name the file movie.php).
  2. Paste the contents of the code-box below into the file.
  3. Call the PHP file from withing your HTML instead of the Flash file, ie. <embed src=”movie.php”….

<?
$max_increase = 50; //how much to allow file size to grow, in kB

$increase = rand(1, ($max_increase * 1024) / 64) * 64; //we’ll stick to 64 byte chunks
$file = basename($_SERVER[“SCRIPT_NAME”], “.php”) . “.swf”; //change if not .swf
$new_size = filesize($file) + $increase;
$data = file_get_contents($file);

header(“Expires: Sat, 26 Jul 1997 05:00:00 GMT”);
header(“Last-Modified: ” . gmdate(“D, d M Y H:i:s”) . ” GMT”);
header(“Cache-Control: no-cache, must-revalidate”);
header(“Pragma: no-cache”);

header(“Content-type: ” . mime_content_type($file));
header(“Content-Length: ” . $new_size);
header(“Content-Transfer-Encoding: binary”);

$data.= str_repeat(chr(0), $increase);

echo $data;
?>