Allow private images to be stored in browsers cache for one week

Public

Get raw version
php
  1. /**
  2.  * Implements hook_file_download().
  3.  *
  4.  * Allow private images to be stored in browsers cache for one week.
  5.  *
  6.  * @param string $uri
  7.  * @return array
  8.  */
  9. function MYMODULE_file_download($uri) {
  10. if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
  11. // ImageCache presets
  12. $ifs = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
  13. if (strpos($uri, 'private://styles') === 0) {
  14. if (REQUEST_TIME < $ifs + 604800) {
  15. header('HTTP/1.1 304 Not Modified');
  16. exit();
  17. }
  18. }
  19. // Regular files
  20. else {
  21. $file = db_select('file_managed', 'fm')
  22. ->fields('fm')
  23. ->condition('uri', $uri)
  24. ->execute()
  25. ->fetchAssoc();
  26.  
  27. if (!empty($file)) {
  28. $modified = $file['timestamp'];
  29. if ($modified < $ifs) {
  30. header('HTTP/1.1 304 Not Modified');
  31. exit();
  32. }
  33. }
  34. }
  35. }
  36.  
  37. // Getting file info
  38. $info = image_get_info($uri);
  39. // For images files
  40. if (isset($info['mime_type']) && strpos($info['mime_type'], 'image/') === 0) {
  41. // cache max-age : 1 week
  42. // expire-date : now + 7*86400 s
  43. // etag using a hash of the file size variable
  44. return array('Cache-Control' => 'max-age=604800, public',
  45. 'Expires' => gmdate('D, d M Y H:i:s', REQUEST_TIME + 604800) . ' GMT',
  46. 'Last-Modified' => gmdate('D, d M Y H:i:s', REQUEST_TIME) . ' GMT',
  47. 'ETag' => strtr(md5($info['file_size']), 0, 10));
  48. }
  49. }

Comments

J-F Bohemier's picture

Thanks for this snippet... it works well