Force no caching with PHP

If you’re a web developer you’ve almost certainly run into web page caching issues. Allow me to explain one situation I found myself in and how I fixed it.

There are times when I’ll test one of my web pages in a browser, see something I need to fix, fix it, refresh, and nothing has changed. Did I save to the right file? Is the fixed coded being skipped over because of some condition not being met? I admit that while it seems painfully obvious now, that I’ve wasted time in these situations trying to figure out what the crap is going on. Eventually I sit back in my chair and get break my mind out it’s infinite loop of failed ideas and realize I’ve been duped. It’s the infamous cached web page of doom! At least that’s what I choose to call it in this article.

A while back I was working on a site that implemented some Ajax. The Javascript made an Ajax call to a PHP page on my server and then handle the response text. It was giving me some strange results, sometimes the response came back as expected, other times it didn’t. But before too long I realized that I was getting cached data. Moral of this story, things are not always what they seem.

So how do you tell a web browser not to cache page data? It’s actually quite easy. In your PHP file you can include some caching instructions in the header. Here’s an example.

header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Mon, 27 Oct 1980 01:00:00 GMT"); // Any old date in the past

The first header line should be self explanatory. The second header line just needs any date in the past, telling the web browser that its cache (if it has one) has expired. It’s nice little trick. Also remember that your header output must come before any other output or you’ll get an error.

I hope this helps save you some time and frustration in your current and future endeavors in PHP web development!