Hook_file_download Drupal 9 ((link)) May 2026
hook_file_download is a critical tool for Drupal 9 developers who need to control access to files served through the private file system . While public files are served directly by the web server (like Apache or Nginx), private files are routed through Drupal, allowing your code to decide who can see what. How hook_file_download Works
use Drupal\Core\StreamWrapper\StreamWrapperManager; /** * Implements hook_file_download(). */ function my_module_file_download($uri) { // Only act on private files. if (StreamWrapperManager::getScheme($uri) === 'private') { $account = \Drupal::currentUser(); // Deny access if the user lacks the required permission. if (!$account->hasPermission('access special documents')) { return -1; } // Grant access and provide headers. $file_repository = \Drupal::service('file.repository'); $file = $file_repository->loadByUri($uri); if ($file) { return [ 'Content-Type' => $file->getMimeType(), 'Content-Length' => $file->getSize(), ]; } } return NULL; } Use code with caution. Important Considerations hook_file_download drupal 9
: This hook is not triggered for public files (those in sites/default/files ) because the web server handles them before Drupal even starts. hook_file_download is a critical tool for Drupal 9
: Providing the necessary headers (like Content-Type ) if access is granted. Implementation Guide */ function my_module_file_download($uri) { // Only act on
: Defer the decision. If your module doesn't care about this specific file, return NULL to let other modules decide. Example: Restricting by Permission
: If one module grants access but another returns -1 , the access is denied.
: For private images, Drupal also uses this hook to check access for the generated image styles . Common Use Cases