Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Passes through image from cache folder to render.
- * @param string $fileName
- * @param string $fileExtension
- */
- public static function renderImageFromCacheFolder($fileName, $fileExtension){
- $filePath = self::getImagesCacheFolderPath(). $fileName . ".". $fileExtension;
- // get the last modification of the image
- $lastModified = filemtime($filePath);
- //Modify last access time by using touch, so when we run cleanCache we can delete all images not accessed in the last 30 days
- // ensure only access time is changed, not modification time, do this by setting new modification time to the
- // previous one, and access time to current time()
- touch($filePath, date('U', $lastModified), time());
- // get a unique hash of this image
- // this is called an etag
- $etagFile = md5_file($filePath);
- // get the HTTP_IF_MODIFIED_SINCE header if set
- // imagine this as the browser saying to your server:
- // "Don't mind sending me the image if it wasn't modified since this date, I already have it then"
- $ifModifiedSince=(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] : false);
- // get the HTTP_IF_NONE_MATCH header if set (etag: unique file hash)
- // imagine this as the browser saying to your server:
- // "Don't mind sending me the image if it has this etag, if file's etag on the server is the same
- // etag that I have, then we have the same image, Don't send it to me, I already have it"
- $etagHeader=(isset($_SERVER['HTTP_IF_NONE_MATCH']) ? trim($_SERVER['HTTP_IF_NONE_MATCH']) : false);
- //set last-modified header
- header("Last-Modified: ".gmdate("r", $lastModified));
- //set etag-header
- header("Etag: $etagFile");
- //make sure caching is turned on
- header('Cache-Control: public');
- //check if page has changed. If not, send 304 and exit
- // if file wasn't modified, or etag still the same
- // then we don't need to send it again
- // we check using "or" because here we use md5_file to get the etag. then *even* if the modified date changes
- // if md5_file stilll returns the same result, the file didn't change at all
- if (($ifModifiedSince && @strtotime($ifModifiedSince)==$lastModified) || $etagHeader == $etagFile)
- {
- header("HTTP/1.1 304 Not Modified");
- exit;
- }
- // at this point we need to send the image to the browser because it's not in browser cache
- header("Content-Type: image/$fileExtension");
- header('Content-Length: ' . filesize($filePath));
- echo file_get_contents($filePath);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement