PHP: header expires not working

3.9k views Asked by At

My PHP code:

$expires_date = date('D, j F Y H:i:s', strtotime('now + 10 years')) . ' GMT';           
header("Expires: $expires_date");
header('Content-type: text/javascript');

echo 'hello world';

When I check the response headers, I see this:

Expires:Thu, 01 Jan 1970 00:00:00 GMT

What am I doing wrong?

UPDATE:

Was just experimenting, but it seems that I can't even unset Expires via header_remove('Expires');. I still see the 1970 date.

UPDATE:

My response headers:

Cache-Control:private
Connection:Keep-Alive
Content-Encoding:gzip
Content-Length:74
Content-Type:text/javascript
Date:Wed, 17 Oct 2012 22:40:45 GMT
Expires:Thu, 01 Jan 1970 00:00:00 GMT
Keep-Alive:timeout=5, max=98
Server:Apache/2.2.21 (Win32) PHP/5.3.9
Vary:Accept-Encoding
X-Powered-By:PHP/5.3.9
3

There are 3 answers

6
WebChemist On

look at your htaccess file:

<FilesMatch "\.(htm|html|php)$">
        Header set Expires "Thu, 01 Jan 1970 00:00:00 GMT"

        # TODO: Google.com's setting are the following
        # Expires -1
        # Cache-Control private, max-age=0
</FilesMatch>

it looks like your FilesMatch .php is overriding the .htaccess Content-Type:text/javascript rule and the PHP expires header because the script is a .php file.

Comment out this header expires in your .htaccess and see if the PHP header +10 year expires still gives the 1/1/1970 date

3
user823738 On

You have formatting errors.

  • Use d instead of j
  • Use M instead of F
  • Use gmdate() instead of date()

From header definitions (14.21):

An example of its use is

 Expires: Thu, 01 Dec 1994 16:00:00 GMT

 Note: if a response includes a Cache-Control field with the max-
 age directive (see section 14.9.3), that directive overrides the
 Expires field.

HTTP/1.1 clients and caches MUST treat other invalid date formats, especially including the value "0", as in the past (i.e., "already expired").

To mark a response as "already expired," an origin server sends an Expires date that is equal to the Date header value. (See the rules for expiration calculations in section 13.2.4.)

To mark a response as "never expires," an origin server sends an Expires date approximately one year from the time the response is sent. HTTP/1.1 servers SHOULD NOT send Expires dates more than one year in the future.

So you shouldnt send Expires with more than one year in the future. Instead to indicate never expires ommit the header or use Expires: -1.

0
Omar Freewan On

Try use :

// To revalidate the headers again

header("Cache-Control: no-cache, must-revalidate");

// Then set expire date

header("Expires: Sat, 26 Jul 2011 05:20:00 GMT"); // Date to expire

it fixed my problem before