Question

I was playing with PHP, using ETags, IF_NONE_MATCH, etc, when a weird thing happened. I wrote the code below, which checks for IF_NONE_MATCH. If it matches my ETag, I send a 304 response header. If not, I send other headers telling the browser to cache the page, and my ETag with them. I was expecting to get the page once, and then get 304's all the time. Instead, I'm getting the page once, then a 304, then the page, then 304, etc. When I checked Chrome's header view I saw that if I hadn't set the ETag again in the 304 code, it doesn't send it back in its request headers next time I get the page. Is this normal behaviour or is it just Chrome? Am I doing something wrong?

Here is the code:

<?php
    $etag = '89453fo245tyu5o423ty5349gu0p34';

    if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && 
                                  $_SERVER['HTTP_IF_NONE_MATCH'] == $etag) {
         header('', true, 304);
    } else {
         header('Expires: Fri, 06 Apr 2013 23:59:59 03:00 GMT');
         header('Pragma: cache');
         header('Cache-Control: public, must-revalidate, max-age=0');
         header('ETag: ' . $etag);
         echo 'new page';
    }
Was it helpful?

Solution

I think the problem is in your header call. Use the correct header call, as mention in this answer and everything should be fine:

header('HTTP/1.1 304 Not Modified');

Also remember that if you press F5 to refresh your page, probably your browser will ignore the cache and go straight to the webserver. To test, I'd add a link to the same page, or just click in the browser address bar and press enter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top