5

Is there a way to cache drupal private images in client browser? I have a website with private profile images that are used many times and I want to cache them even for a very few time. How can I do that?

Thanks

2

I finally found how to handle it : there is a hook_file_download where i can add and set header for the file :

function mymodule_file_download($uri){


// Getting file info
  $info = image_get_info($uri);

  // For images files
  if(isset($info['mime_type']) && strpos($info['mime_type'], 'image/') === 0){
    // cache max-age : 1 day 
    // expire-date : now + 86400 s
    // etag using a hash of the file size variable
    return array('Cache-Control' => 'max-age=86400, private',
                 'Expires' => gmdate('D, d M Y H:i:s', time() + 86400) .' GMT',
                 'Last-Modified' => gmdate('D, d M Y H:i:s', time() - 86400) .' GMT',
                 'ETag' => strtr(md5($info['file_size']), 0, 10));
  }
}
2

From https://drupal.org/node/1844126#comment-8215137, a version that does not grant access to all files:

/**
 * Implements hook_file_download().
 */
function mymodule_system_file_download($uri) {
  if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
    $ifs = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
    $file = db_select('file_managed', 'fm')
      ->fields('fm')
      ->condition("uri", $uri)
      ->execute()
      ->fetchAssoc();
    if (!empty($file)) {
      $modified = $file['timestamp'];
      if ($modified < $ifs) {
        header($_SERVER['SERVER_PROTOCOL'] . ' 304 Not Modified');
        exit();
      }
    }
  }
  // Don't return headers to avoid granting access to all files.
  $max_age = variable_get('page_cache_maximum_age', 0);
  drupal_add_http_header('Cache-Control', 'private, max-age=' . $max_age);
  drupal_add_http_header('Last-Modified', gmdate(DATE_RFC1123, REQUEST_TIME));
  drupal_add_http_header('ETag', strtr(md5($uri), 0, 10));
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.