2

I have implemented a private file system for users to upload files. This appears to be working as I can see that the file is uploaded into the proper directory. The problem I have is that no one has permission to view the file (including user 1 which seems odd to me). The error message is:

You are not authorized to access this page.

From what I have read in the documentation, I believe I have everything set up correctly. The file path is outside of the web root directory and accessible by Drupal (as evidenced by the successful file upload). The page that displays the link to the file is in the form of:

/system/files/private/test.pdf

Which is the correct link.

The file permissions set on the directory is: drwxrwxr-x

Which looks right to me as well.

So I am completely stumped. I followed the Drupal 7 documentation page on setting up private directories so I am not sure what I missed. I have obviously overlooked something and hope that someone can tell me what it is or what I should be looking for or what I need to implement to get this working. This is for Drupal 7 by the way.

Thanks

4

After digging around some more I have found the solution. In your module you need to implement the hook_file_download() function. This function determines whether a user has the permission to view the file. It should look something similar to this:

function my_module_file_download($uri) {

  // Get the file record based on the URI. If not in the database just return.
  $files = file_load_multiple(array(), array('uri' => $uri));
  if (count($files)) {
    foreach ($files as $item) {
      // Since some database servers sometimes use a case-insensitive comparison
      // by default, double check that the filename is an exact match.
      if ($item->uri === $uri) {
        $file = $item;
        break;
      }
    }
  }

  if (!isset($file)) {
    return;
  }

  // Put your permission check code here.
  $can_access_file = check user permission function

  // When done perform the following code    
  if ($can_access_file) {
    $headers = file_get_content_headers($file);
    return $headers;
  }  
  return -1; // return that user does not have access
}

Hopefully this will help others with similar problems.

  • I guess a comment I have is this permits you to download a file, but what if you only want to view it??? – user5013 Jan 28 '13 at 19:32
1

In my case, I could access private image files on my stage server but not on live.

The cause was: on the live server's settings.php, Fast 404 pages was enabled.

I needed to replace this line:

$conf['404_fast_paths_exclude'] = '//(?:styles)//';

... with this ...

$conf['404_fast_paths_exclude'] = '//(?:styles)|(?:system/files)//';

See: https://www.drupal.org/node/2455057

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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