11 Eylül 2007 Salı

Expires Header in PHP

Expires header tells the client about the freshness of the page. If it is configuered properly the server sends an expires header with other headers to the client. This is an important information for the client. It means that the page is fresh only till the expiry time. So till this expiry time client can cache the page and after it is expired client need to contact the server for a fresh page.

For example if the expiry time is set to 1 hour then client will keep the page in cache and if somebody request to open the site within 1 hour then browser will load it from the cache. After one hour if a user open the site in the browser then browser will contact the server again to get a fresh page.

To send an expires header first you have to decide about the freshness period or expiry period. It purely depdends upon your site and will vary site to site.. For example for a news site the pages will be updated frequently or every hour while for a simple personal site it may be weeks or months.

Suppose you are updating your pages every day then set the expiry date for 24 hours. To set the expiry time you have to convert it in to seconds. i.e.

$expirytime=24 * 60 * 60;

Now we have to add it with current time

$expirytime=time() + $expirytime;

Now format it to GMT/UTC date/time

$expires = gmdate("D, d M Y H:i:s", $expirytime) . " GMT";

Finally send the header with header function.

header("Expires: " . $expires);

This will send a header to the client like this

Expires Sat,08 Jul 2006 17:19:05 GMT

This means the page is fresh only till this time and date. After this time the client need to contact the server again for a refreshed page.

Always you have to take special care while sending a header to the client because you have to make sure that the header info should go first before outputing anything.

Hiç yorum yok: