How do I restrict the access to certain files based on their content type? I have the download section for registered users, and I want to prevent them to post links somewhere outside my site.

Is implementing hook_file_download() sufficient?

I tried this code and it's enough for my purpose, but the documentation of hook_file_download() doesn't help much.

function customize_file_download($uri) {
  global $user;
  if (!array_intersect(array('administrator','editor','expert','verified'), array_values($user->roles))) {
    return −1;
  • Maybe I post example and I hope it helps visualize it I have content_type file with field file (set private download method) then I need protect this file from accessing it unauthorized persons(based on user role)? What is the best aproach? Simply check it user have right role in hook_file_download and thats all? – Pari Jun 9 '11 at 14:23

There is a couple of hooks in drupal 7 to restrict access to files.

One thing you have to realized is that these access hooks are only going to work if your download method is private, and the files are in your private path.

As you mention in your question there is a hook_file_download that should work in your case (assuming the file is private). This is not going to work if the file, someone is linking to, is somewhere public such as sites/default/files/abc123.txt.

If you happened to be uploading these private files in a field, then hook_file_download_access would seem more appropriate. This will give you the field that the file belongs to and also the related entity that this field is being used on so you should be able to do more complicated logic such as calling the the appropriate access function to check if the user has access to the field instead of having a hard-coded list in the code.

| improve this answer | |
  • hook_file_download with private file system doesn't invoke for anonymous users. Any idea why? – Jeet Dec 3 '13 at 5:21
  • 1
    i think because anonymous users are not supposed to access the private files. – DrCord Jul 30 '14 at 22:59

A link to a file is just that - a link. I don't believe there is a way to determine the location of the link. You might be able to look at headers, but this will probably not work.

If you can determine the location of the link to the file, using hook_file_download will be a good choice for access control.

| improve this answer | |

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.