/Drupal 8

function image_file_download


Implements hook_file_download().

Control the access to files underneath the styles directory.


core/modules/image/image.module, line 169
Exposes global functionality for creating image styles.


function image_file_download($uri) {
  $path = file_uri_target($uri);

  // Private file access for image style derivatives.
  if (strpos($path, 'styles/') === 0) {
    $args = explode('/', $path);

    // Discard "styles", style name, and scheme from the path
    $args = array_slice($args, 3);

    // Then the remaining parts are the path to the image.
    $original_uri = file_uri_scheme($uri) . '://' . implode('/', $args);

    // Check that the file exists and is an image.
    $image = \Drupal::service('image.factory')->get($uri);
    if ($image->isValid()) {
      // Check the permissions of the original to grant access to this image.
      $headers = \Drupal::moduleHandler()->invokeAll('file_download', array($original_uri));
      // Confirm there's at least one module granting access and none denying access.
      if (!empty($headers) && !in_array(-1, $headers)) {
        return array(
          // Send headers describing the image's size, and MIME-type.
          'Content-Type' => $image->getMimeType(),
          'Content-Length' => $image->getFileSize(),
          // By not explicitly setting them here, this uses normal Drupal
// Expires, Cache-Control and ETag headers to prevent proxy or
// browser caching of private images.
    return -1;

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.