I'm building a page with different download buttons linked to private zip files. Users have to log in to download. I am using module Permissions by Term to manage who can see which button.
I added a field to user entity to log each download. In hook_file_download() I check, if and how often this file is already downloaded by this user. Up to here everything works fine.
I want to stop or block the download and show a message to the user, if download counter reaches 5 or 10. Is hook_file_download the right hook to achieve this?

  • 3
    Check the hook documentation. If you return -1, it won’t serve the file.
    – Kevin
    Oct 31, 2019 at 1:49
  • Thanks, but @STF solution is cleaner for me. Actually I can omit the message and redirect the user to a page with some explanation.
    – krabbe
    Oct 31, 2019 at 16:42

1 Answer 1


I have this to check that the users has remaining downloads or redirect them to an upgrade page.

 * Implements hook_file_download().
function mymodule_file_download($uri) {
  // Check if user is logged in
  if (\Drupal::currentUser()->isAuthenticated()) {
    // Load entity of current user
    $current_user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

    // Check if current user is: access || student || (professional && trial_actived)
    $download_control = $current_user->hasRole('professional') && $current_user->field_user_free_trial->value == 'trial_actived' ? TRUE : FALSE;
    $download_control = $download_control || $current_user->hasRole('access') || $current_user->hasRole('student') ? TRUE : FALSE;

if ($download_control) {

  // Declare files that decrease the counter
  $controlled_uris = [

  // Check if requested uri matches with controlled uris
  foreach ($controlled_uris as $c_uri) {
    if (strpos($uri, $c_uri) !== FALSE) {

      // Check if user still has remaining downloads
      if ($current_user->field_user_download_counter->value > 0) {

        // Decrease user downloads counter
      else {
        // Prepare redirect url to the prices page
        $url = \Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => 39])->toString();

        // Set message
        $message = t('Your account has reached the maximum limit of downloads.');

        // Send response to url
        $response = new \Symfony\Component\HttpFoundation\RedirectResponse($url);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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