3

There is a lot of advice how to use headers to prevent the browser from caching a file. I wish to do the opposite. The cache.php file below never changes. I've tested this using FF, Chrome, and FF, and each time index.html is reloaded, the cache.php is downloaded from the server. How do I tell the browser to cache the JavaScript file "cache.php"? Thank you

index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> 
        <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" /> 
        <title>Testing</title>  
        <script src="cache.php" type="text/javascript"></script> 
    </head>
    <body>
        <p>Hello!</p>
    </body> 
</html> 

cache.php

<?php
    syslog(LOG_INFO,'cache.php'.rand());
    header( 'Content-type: text/javascript' );
    echo('alert("Hello!");');    
?> 
Charles
  • 50,943
  • 13
  • 104
  • 142
user1032531
  • 24,767
  • 68
  • 217
  • 387
  • If it never changes, why don't you just save the generated file and use that as the js source? This way you won't have to fiddle around with http cache headers in php and can let the http server software do that job for you instead. – Hauke P. Jun 01 '13 at 16:50
  • @HaukeP. It is a bunch of data generated by a DB, and it is much easier to maintain by pulling the data from the DB, and not creating a separate file. I have a similar application for downloading images. My images are served by PHP so that I can control who can view. I would like the server to send the image to the client the first time, but for the client to use cached images for future requests. – user1032531 Jun 01 '13 at 17:00

1 Answers1

0

You'll have to implement cache handling in PHP. Check this question and its answers for details: How to use HTTP cache headers with PHP

Community
  • 1
  • 1
Hauke P.
  • 2,695
  • 1
  • 20
  • 43
  • There were multiple responses on that post. When looking at `$_SERVER` (or `apache_request_headers();`), I don't have `$_SERVER['HTTP_IF_MODIFIED_SINCE']`. – user1032531 Jun 01 '13 at 17:18
  • (The following is a simplification.) `If-Modified-Since` is an http header that the browser sends out if it has the requested page stored in its cache. However, a browser needs to know a page's modification date in order to store it in the cache. Therefore, you'll have to send out a header in which you tell the browser the neccessary date, e.g. like this: `header("Last-Modified: $yourdate");`. Once the browser receives your page with that header, it wil store it in the cache and provide the `Is-Modified-Since` header when requesting it the next time. Your code has to react accordingly then. – Hauke P. Jun 01 '13 at 18:54