Stop files being accessed directly

2019-08-16 08:58发布

问题:

I was wondering, I have made a php plugin for wordpress which asks as an image store. If you login you see the files which you have been assigned. Then you click download and it downloads them.

The trouble is, if you know the URL you can download the image regardless. How can I easily stop users from downloading the image if they know its unique URL, and instead only allow those people who have login permission to view it.

The ideas I have are either:

  1. Some kind of HTACCESS hack which checks the refering URL
  2. A kind of KEY system, which only allows the file to be downloaded if a key is supplied.

Any information or ideas would be really useful, thank you.

回答1:

If you make the images unreadable for the world (directory outside the www dir for instance, or just block it with a .htaccess (no need for referral check) you can be sure that nobody can access your image.

Then serve your image through a file (e.g. getImage.php?imageid=xxxx) that checks credentials, and if OK then reads the image (your php process can read the image, e.g. with file_get_contents() ) and then serve it up.

(use the correct header and you'll be fine: header("content-type: image/your_image_type"); )



回答2:

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?mydomain.com/.*$ [NC]
RewriteRule \.(gif|jpg|js|css)$ - [F]

Be sure to replace "mydomain.com" with your own. The above code creates a failed request when hot linking of the specified file types occurs. In the case of images, a broken image is shown instead.



回答3:

To secure a file you can do one of following two things

  1. Place the file in a secure area (out of your public accessible folder). Have its name stored in database and when somone clicks on download you pick that file up and let them download it.
  2. Never reveal the file url to public. When someone wants to download an image they will click on download and you can use timestamp to generate a unique filename at that time and transfer the download with alias filename. Obviously the file wont actually exist on the server. You are just picking up the original file and changing its name so when someone recieves it they would not be able to guess its path. However if by some reason the path went out public then they can access the file.

Option 1 is mostly used when people store documents signatures etc Option 2 can be used if you dont have access to such folders like in shared hosting environment etc.