Forum Moderators: phranque

Message Too Old, No Replies

How do you enable client-caching for PHP pages?

         

smithaa02

4:34 pm on Jun 5, 2006 (gmt 0)

10+ Year Member



Is there something I can add to my .htaccess file that would enable this?

Basically, I recently updated all my .html files to run as php files (to enable SSI type header/footer templates for SEO friendly .html pages). I inserted addtype application/x-httpd-php .html .htm into my .htaccess file, and my .htm pages now work fine as php pages. My problem is that the pages now do not cache themselves on the client. Now I understand why this would normally happen because PHP can be dynamic, but is not applicable in my case because I'm just using the php for header/footer templates. So checking mypage.htm for its modification date before recieving content like a normal .html page would work in my case.

Does anybody know how to do this?

jdMorgan

5:57 pm on Jun 17, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Bump...

BarryStCyr

6:14 pm on Jun 17, 2006 (gmt 0)

10+ Year Member



I hate to give up trade secrets, but I found this somewhere. I don't remember where, so I can't give attribution.

You can adjust cache time to however long you like.

Place this section at the beginning of your code.


[pre]
<?php
$cachetime = 3600;
if (isset($headers['If-Modified-Since']) && (strtotime($headers['If-Modified-Since']) > (time()-3600)))
{
// Client's cache IS current, so we just respond '304 Not Modified'.
header('Last-Modified: '.gmdate('D, d M Y H:i:s', (strtotime($headers['If-Modified-Since']))).' GMT', true, 304);
exit();
}
header('Last-Modified: '.gmdate('D, d M Y H:i:s', (time()-$cachetime)).' GMT', true, 200);
ob_start();
?>
[/pre]

Place this at the end.

[pre]
<?php
SendLength();
function SendLength()
{
if(ob_get_length())
{
header("Content-Length: ".ob_get_length());
ob_end_flush();
die;
}
}
?>
[/pre]

This has the added benefit of outputting the file size just like a true html document.

Hope this helps.
Barry

BarryStCyr

6:18 pm on Jun 17, 2006 (gmt 0)

10+ Year Member



I should add that this method will slow the delivery of your page to the user. It waits until the page is completely created before sending the information so it can determine the page length.

Thanks
Barry