PDA

View Full Version : Can the cache be disabled?



Yesideez
04-25-2005, 01:10 PM
I've got a page that uses a verification code that's being created using PHP via an include file.

The problem I've got is that if the user enters the wrong code the page refreshes and a new code is generated but the image remains the same. Is there any safe way of disabling the cache for that image or even a way of setting the life of the page to one second so that the page expires before the user has a chance of entering the code?

My main script contains this at the start:

header("Expires: Sat, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cache-Control: post-check=0, pre-check=0",false);
session_cache_limiter('nocache');
session_start();
and my this is my include file:

session_start();
$rand=rand(10000,99999);
$_SESSION['chkcode']=md5($rand);
$image=imagecreate(45,14);
$bgColor=imagecolorallocate($image,8,12,109);
$textColor=imagecolorallocate($image,255,255,255);
imagestring($image,4,0,1,$rand,$textColor);
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0",false);
header("Pragma: no-cache");
header('Content-type: image/jpeg');
imagejpeg($image);
imagedestroy($image);

The include file is being called like this:

<img src="rndimage.php" border="0" />
Many thanks.

mwinter
05-01-2005, 12:38 AM
Pretty much any dynamically-generated resource should be considered uncachable if left as-is because it won't send any validators or freshness information.

Could you provide a minimal, testable demonstration and the source code? I didn't need to do anything special to prevent caching in my tests, so it would be better to see something that does fail.

It is possible that you're trying too hard. For a start, the session_cache_limiter will already set a variety of cache-related headers.

For the record, values for the Expires header should either be current or in the future. They should not be in the past. RFC 2616 (HTTP/1.1) states that resources will be considered stale if the Expires date matches that of the Date header. In other words, it expired as soon as it was sent. The simple solution would be to use the Last-Modified header generation code you currently have to generate the Expires header.

Mike