views:

316

answers:

2

I am using a PHP script to serve files. I would like to be able to send back a 304 not modified header in my http response if the file has not changed since the client last downloaded it. This seems to be a feature in Apache (and most other web servers), but I have no clue how this can be implemented through PHP.

I have heard of using $_SERVER['HTTP_IF_MODIFIED_SINCE'], but this variable does not seem to appear in my $_SERVER super array.

My question is not how to return a 304 header, but how to know that one should be returned.


Edit: The problem is that my $_SERVER['HTTP_IF_MODIFIED_SINCE'] is not set. This is the content of my .htaccess file:

ExpiresActive On 
ExpiresByType image/jpeg "modification plus 1 month"
ExpiresByType image/png "modification plus 1 month"
ExpiresByType image/gif "modification plus 1 month"
Header append Cache-Control: "must-revalidate" 


<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteCond $1 !^(controller\.php)
   RewriteRule (.*\.jpg|.*\.png|.*\.gif) controller.php/$1
</IfModule>

HTTP_IF_MODIFIED_SINCE still does not appear in the $_SERVER super array.

+1  A: 

HTTP_IF_MODIFIED_SINCE is the right way to do it. If you aren't getting it, check that Apache has mod_expires and mod_headers enabled and working properly. Borrowed from a comment on PHP.net:

$last_modified_time = filemtime($file); 
$etag = md5_file($file); 
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $last_modified_time)." GMT"); 
header("Etag: $etag"); 
if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified_time || 
    trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) { 
    header("HTTP/1.1 304 Not Modified"); 
    exit; 
}
cpharmston
I have seen this way of doing this, but $_SERVER['HTTP_IF_MODIFIED_SINCE'] is always empty for me...
jd
Check my recent edit -- I left out a piece of important Apache config info.
cpharmston
Tried to modify my htaccess.txt file as per http://www.webmasterworld.com/forum23/2300.htm, but no go. Any ideas?
jd
There's no such thing as htaccess.txt file. It must be .htaccess file
andho
A: 

$_SERVER['HTTP_IF_MODIFIED_SINCE'] is usually empty when register_globals is off...

check whether that's the case, in which case try getenv('HTTP_IF_MODIFIED_SINCE')

pǝlɐɥʞ