Before you read this please note: I DO NOT want to disable browser cacheing. I need it to reduce bandwidth costs.
I wrote some PHP code to output an image which will be cached by the browser (see code below). This is pretty common and I've seen examples just like this all over the place. Everything works fine. But....
What if there is an error half way through outputting the image? Half of the image gets cached!!! The next time you load the page only half the image shows up! This can happen if apache gets restarted, if the server is rebooted, if theres a power outage, if there is a bug in the code, etc.
It may not be too bad for images, but I was thinking of doing the same thing with flv files, which take longer to download (therefore more room for something to go wrong).
Is there a way to tell the browser to only cache the image after the WHOLE image gets downloaded? I there some other solution?
I searched for days and I'm surprised that I couldn't find a single article about this.
Here is a simplified version of my code. I know this code is not secure but its just an example.
Code: Select all
<?php
// Figure out which image to send them
$image = $_GET['image'];
$fsize=filesize("C:/path/to/image/$image");
$fh = fopen("C:/path/to/image/$image", "rb");
header("Content-type: image/jpeg");
header('Content-length: '. $fsize);
header("Cache-Control: must-revalidate");
//Set to expire in 3 days
$offset = 60 * 60 * 24 * 3;
$ExpStr = "Expires: " . gmdate("D, d M Y H:i:s", time() + $offset) . " GMT";
header($ExpStr);
while (!feof($fh))
{
$buffer=fread($fh, 1024);
//what is something goes wrong here?
if ($buffer===FALSE)
{
fclose($fh);
exit(1);
}
echo $buffer;
}
exit(0);
?>