note 52040 deleted from function.header by sp

From: Date: Sun, 03 Jul 2005 13:52:52 +0000
Subject: note 52040 deleted from function.header by sp
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-91359@lists.php.net to get a copy of this message
Note Submitter: Philipp Heckel ---- Sending image files through PHP is very easy, if you don't want to use the browser cache. As soon as you like to use the cache, it is getting a little more complicated. As it isn't possible to define all headers by yourself, and PHP likes sending 'Pragma: no-cache', 'Cache-Control: ...' and other funny headers preventing the browser of caching the file, we need to modify these lines. <?php # check if valid if (!@file_exists($filename) || !@is_readable($filename)) die("The selected Image does not exist."); else $lastmod = @filemtime($filename) or die("Error while trying to read the 'Last Modified'-Information."); # check if 'sending' is necessary (using cache functions) $sendbody = true; # get file content $content = file_get_contents($filename); $etag = '"'.md5($content).'"'; # check 'If-Modified-Since' header if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && gmdate('D, d M Y H:i:s', $lastmod)." GMT" == trim($_SERVER['HTTP_IF_MODIFIED_SINCE'])) { header("HTTP/1.0 304 Not Modified"); header("ETag: {$etag}"); header("Content-Length: 0"); $sendbody = false; } # check 'If-None-Match' header (ETag) if ($sendbody && isset($_SERVER['HTTP_IF_NONE_MATCH'])) { $inm = explode(",",$_SERVER['HTTP_IF_NONE_MATCH']); foreach ($inm as $i) { if (trim($i) != $etag) continue; header("HTTP/1.0 304 Not Modified"); header("ETag: {$etag}"); header("Content-Length: 0"); $sendbody = false; break; } } # caching headers (enable cache for one day) $expires = 60 * 60 * 24; $exp_gmt = gmdate("D, d M Y H:i:s",time()+$expires)." GMT"; $mod_gmt = gmdate("D, d M Y H:i:s",$lastmod)." GMT"; header("Expires: {$exp_gmt}"); header("Last-Modified: {$mod_gmt}"); header("Cache-Control: public, max-age={$expires}"); header("Pragma: !invalid"); # send image if ($sendbody) { $size = @filesize($filename) or openError("Error while trying to read the Filesize",lastURI()); header("ETag: {$etag}"); header("Content-Type: image/jpeg"); header("Content-Length: {$size}"); echo $content; } # don't send else { header("Content-Type: !invalid"); } exit; ?> Note that both Firefox and the IE reload the image if the 'Content-Type: !invalid'- and the 'Pragma: !invalid'-lines are left out. I tried 'Content-Type: ' and 'Pragma: ', but this did not work. Instead of these !invalid-values, you can use session_cache_limiter("public") before starting the session with session_start(). This will also avoid sending the Pragma-header. Philipp Heckel

« previous php.notes (#91359) next »