tags:

views:

109

answers:

1

I'm setting what I think are the correct HTTP Headers for caching from PHP and am getting a 500 error on every second request.

Can anyone point me in the right direction?

The code doing the caching is:

<?php
header('Content-Type: text/css');
$content = file_get_contents('test.css');
header('Content-Length: '. strlen($content ));

$expires = 3600;
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
  // Split the If-Modified-Since (Netscape < v6 gets this wrong) 
  $modifiedSince = explode(';', $_SERVER['HTTP_IF_MODIFIED_SINCE']); 

  // Turn the client request If-Modified-Since into a timestamp 
  $modifiedSince = strtotime($modifiedSince[0]); 
  $current_time = time();
  if (($current_time - $modifiedSince) < $expires) {
    header("304 Not Modified");

    //echo $current_time - $modifiedSince;
    exit();
  }
}

$current_time = time();
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $current_time)." GMT");
header("Expires: " . gmdate("D, d M Y H:i:s", $current_time+$expires) . " GMT");
header("Cache-Control: max-age=$expires"); 
echo $content;

Thanks

Edit 1: I've cleared my cache with no joy and someone reports it working for them. Does this imply a server configuration problem? It's on a hosted server if it matters.

Edit 2: Seems not to happen in IE, but does happen in Firefox

+3  A: 

When I ran your code I wasn't getting a Status 500 error, but I was seeing an every other request "serve the file, serve a blank page" behavior similar to what you described.

It looks like you're not using the header() function correctly when you're setting the status 304. You're missing the "HTTP/1.1". This means that PHP is sending back a Status 200 header, and then exiting with no output. Try

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

If you really ARE getting a Server 500 error on every other request, poke around your webserver (Apache?) logs to see what kind of errors are popping up.

Alan Storm
Putting HTTP/1.1 worked like a charm.
Allain Lalonde