1

My private files has a visible URL like the following: https://mywebsite.com/system/files/myimage.jpg.

How can I restrict access to the file, so it cannot be viewed directly from this URL but only from link on my website?

I have tried to use SESSION as follows.

$_SESSION['file-access'] = TRUE;
$output = theme('image_style', array('style_name' => 'foto_preview', 'path' => $uri));

Then I controlled in hook_file_download() if the SESSION key 'file-access' exists, but the session key never exists. The image I wish to display is the value of an image field. I cannot use $user because I wish to display private files also for anonymous users.

Can anybody help on how to restrict the direct access to a private file, but allow access from website?

EDIT 30.7.2013: my mistake, using sessios works OK, I had a mistake in another unrelated part of code. The problem is solved.

2

You need to use private filesystem as shown in documentation. Then you can create custom module to implement more advanced rules, like link timeouts et cetera.

  • I am using private filesystem. The problem is, how apply this system specifically for my situation. I have set my image field as private files and I am using hook_file_download. But how should I solve my problem? Link timeouts doesn't solve exactly the problem, there is still chance to use the timeout for unallowed visit. – tomas.teicher Jul 29 '13 at 20:16
1

You can do this similar with hot linking htaccess protection.

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?mydomain.tld/.*$ [NC]
RewriteRule \.(gif|jpg)$ http://www.mydomain.tld/image_or_page_to_show_instead [R,L]

Just put your condition instead \.(gif|jpg)$

  • 2
    +1, but it has to be pointed out that referer comes from the client and this protection is easily circumvented. – Letharion Jul 29 '13 at 9:34
  • I can't understand what you are really trying to do. User can download file if only he visited any site page before? I can emulate this with curl, save session && cookies and then download file. So, what kind of profit you are wanna to reach. :) – Oleg Sherbakov Jul 29 '13 at 10:17
  • I tried to use session (as it is code snippet in question) but for an unknowned reason, I cannot get the session value in hook_file_download. The best solution for me to use the $_SESSION, if it works somehow. – tomas.teicher Jul 29 '13 at 20:19
  • As pointed by Letharion, I am afraid, that skilled programmers can circumvent the restriction – tomas.teicher Jul 29 '13 at 20:23
  • The sessions works in hook_file_download, I have mistake in other place in code. The solution is in code snippet in question. – tomas.teicher Aug 11 '13 at 5:28

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.