[Drupal] File download using hook_file_download() and hook_file_download_access()

| | 1 min read

The purpose of hook_file_download is to Control access to private file downloads and specify HTTP headers. The hook_file_download_access is restrict the access to certain files based on the entity type. e.g.,
only users with access to a node should be allowed to download files attached to that node.

If the return value is TRUE then its accessible otherwise it denied. To understand File download using hook_file_download() and hook_file_download_access(), please read on.


/**
 *  Page call back function.
 */
function custom_download($file_id) {
  if (isset($file_id)) {
    $file = file_load($file_id);
    if (isset($file->filename)) {
      /** file_download() -> Menu handler for private file transfers.
       * Call modules that implement hook_file_download() to find out if a file is accessible.
       */
       file_download('private', 'foldername/' . $file->filename);
    }
  }
}

/**
 * Implementation of hook_file_download().
 */
function module_name_file_download($uri) {
  $files = file_load_multiple(array(), array('uri' => $uri));
  if (!empty($files)) {
    foreach ($files as $file) {
      $filename = $file->filename;
    }
    return array(
      'Content-type' => file_get_mimetype($uri),
      'Content-disposition' => 'attachment; filename=' . $filename
    );
  }
}

/**
 * Implements hook_file_download_access()
 */
function module_name_file_download_access($file_item, $entity_type, $entity) {
  /**
   * your conditions here.
   */
   return TRUE is access should be allowed by this entity or FALSE if denied
}

Please let us know if we can be of any further help.