function file_example_file_download

Implements hook_file_download().

This hook allows modules to enforce permissions on file downloads whenever Drupal is handling file download, as opposed to the web server bypassing Drupal and returning the file from a public directory. Modules can also provide headers to specify information like the file's name or MIME type.

For our example module, we want to be able to see the temporary, private, and session (our test stream wrapper / file scheme). In general, you really would NEVER give general access to your temporary, and you certainly wouldn't do it for your private files. So we demonstrate this here, but don't try this at home. Remember: keep your files secure!

For hook_file_download() to get called at all, your code needs set up your routes so that the download link uses FileDownloadController::download() as a controller. FileDownloadController::download() enforces access restrictions on the files it managed, in part by invoking hook_file_downloads(). Check the routing file used by this module to see how to achieve this.

Parameters

string $uri: The file URI.

Return value

mixed If the current user does not have the permission to access the file, return -1; otherwise, return an array with the appropriate headers. If the file is not controlled by a module, that module should return NULL.

See also

\Drupal\system\FileDownloadController::download()

Related topics

File

modules/file_example/file_example.module, line 79

Code

function file_example_file_download($uri) {
  $scheme = StreamWrapperManager::getScheme($uri);
  if (in_array($scheme, [
    'private',
    'temporary',
    'session',
  ])) {
    $permission = "read {$scheme} files";
    $current_user = \Drupal::currentUser();
    $account = $current_user->getAccount();
    if ($account->hasPermission($permission)) {
      // If the current user has the permission to access the file, return an
      // array with the appropriate headers.
      return [
        'Content-Type: text/plain',
      ];
    }
  }
  // If the current user does not have the permission to access the file, return
  // -1. This is what FileDownloadController::download() expect to obtain in
  // that case.
  return -1;
}