Hook_file_download | Drupal 8 Example |verified|
name: 'My File Security' type: module description: 'Controls access to private file downloads.' core_version_requirement: ^8 || ^9 || ^10 package: Custom Use code with caution. 2. Implement the Hook Now, we implement the logic inside your .module file. my_file_security.module
If all modules return NULL , and no one grants access, Drupal defaults to access denied. The Example: Restricting Downloads by User Role
Before jumping into the code, it’s important to understand the "Private" file system. This hook triggers for files stored in the private:// URI scheme. Files in the public:// folder are served directly by the web server (Apache or Nginx), bypassing Drupal’s PHP layer entirely for performance reasons. hook_file_download drupal 8 example
Check if another module is returning -1 earlier in the execution order, which would override your "allow" logic.
getStorage('file') ->loadByProperties(['uri' => $uri]); if (empty($files)) return NULL; $file = reset($files); $mime_type = $file->getMimeType(); // 2. Check if the file is a PDF. if ($mime_type == 'application/pdf') $current_user = \Drupal::currentUser(); // 3. Logic: Only 'premium_member' or 'administrator' can download. if (in_array('premium_member', $current_user->getRoles()) // For non-PDF files, return NULL to let other modules or Drupal core decide. return NULL; } Use code with caution. Key Takeaways for Developers name: 'My File Security' type: module description: 'Controls
First, ensure you have a custom module. We'll call ours my_file_security . my_file_security.info.yml
When a user requests a private file, Drupal invokes hook_file_download . If any module returns -1 , access is denied (403). If a module returns an array of headers, access is granted. my_file_security
Let’s say we want to ensure that only users with the "Premium Member" role can download PDF files stored in the private directory. 1. Create your Module