Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
592 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);
// always send headers
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $last_modified_time)." GMT"); 
header("Etag: $etag"); 
// exit if not modified
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; 
}

// output data

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...