How to force browser to use already downloaded and cached file.
If you have images in DB, they will reload each time user views them. To prevent this, web server must identify each file with ID.
When sending a file, web server attaches ID of the file in header called ETag.
header("ETag: \"uniqueID\");
When requesting file, browser checks if the file was already downloaded. If cached file is found, server sends the ID with the file request to server.
Server checks if the IDs match and if they do, sends back
header("HTTP/1.1 304 Not Modified");
else
Server sends the file normally.
codice:
<?php
$file = getFileFromDB();
// generate unique ID
$hash = md5($file['contents']);
$headers = getallheaders();
// if Browser sent ID, we check if they match
if (ereg($hash, $headers['If-None-Match']))
{
header('HTTP/1.1 304 Not Modified');
}
else
{
header("ETag: \"{$hash}\"");
header("Accept-Ranges: bytes");
header("Content-Length: ".strlen($file['content']));
header("Content-Type: {$mime}");
header("Content-Disposition: inline; filename=\"{$file['filename']}\";");
echo $file['content'];
}
exit();
?>