Cache-control is a response header. (edit: It is actually also a request header. Thanks for Gumbo for pointing it out.) You need to add such headers in the response (data that PHP sends).
// How long my cache should last
$cacheDuration=300; // in seconds
// Client is told to cache these results for set duration
header('Expires: '.gmdate('D, d M Y H:i:s',($_SERVER['REQUEST_TIME']+$cacheDuration)).' GMT');
header('Last-modified: '.gmdate('D, d M Y H:i:s',$_SERVER['REQUEST_TIME']).' GMT');
// Pragma header removed should the server happen to set it automatically
// Pragma headers can make browser misbehave and still ask data from server
You should actually do it better than that however. Cache-control headers only tell a single client how to maintain that data, another user might still make your server re-do this whole thing. This is what a smart cache system would look like:
- You generate your JSON, whatever it is.
- You store that JSON in your filesystem as a temporary file.
- You send the contents to client with the Cache-control headers, making the browser not request the data from the server again and use cache instead.
- If another user comes to the site and their browser does not have that cache, your script should check if the cache file (that you created in point 2) exists, if it exists then you read data to the client from that file instead of generating it again.
- You should also check how old the cache file is, maybe generate the file again every few days.
But there are a lot of things you need to pay attention to when doing this, if your cache includes sensitive information then you have to make sure that this is not forwarded to wrong clients from cache.
Live example is here: http://waher.net/cachetest.php (the same code as shown above).
This file is loaded by browser from cache for 5 minutes. But note that if you refresh the page, it ignores browser cache and still makes a request to the server. You can try it better if you open a new tab instead of refresh the page and enter the URL and Firebug/Chrome Dev Tools will show that the file was loaded from cache.