Restrict access to images on my website except through my own htmls

linux, perl, php, python

Solution

Method #1 is not viable as it will ask for user name and password on each and every image requested. You probably got the prompt for some of the images and not for others due to caching issues.

Method #2 looks the most appealing to me by being the least processor intensive, but with only the user_id passed through the md5 function the file name still quite easily guessable. You should go for md5('my secret string'.$user_id) for a better solution.

Why are you picking #3 via Perl or Python? What's wrong with PHP's speed? Indeed if you're protecting your images this way you should go to the extra length of moving them out and above your webroot so they're only accessible via your script which first checks if the user is authenticated and then passes the avatar by reading it and outputting it. Alternatively, you could protect the directory with an htaccess file saying `deny from all`.

Plus you should go for a HTTP_REFERER security either via PHP or via .htaccess.

Good luck!

Problem

On my website I store user pictures in a simple manner such as: "image/user_1.jpg". I don't want visitors to be able to view images on my server just by trying user_ids. (Ex: www.mydomain.com/images/user_2.jpg, www.mydomain.com/images/user_3.jpg, so on...) So far I have three solutions in mind: I tried using .htaccess to password protect the "images" folder. That helped me up to some point but some of the images started popping up a username and password request on my htmls (while amazingly some images did not) so this seems to be an unpredictable method. I can start converting my user_id's to an md5 hash with some salt. The images would be named as: /image/user_e4d909c290d0fb1ca068ffaddf22cbd0.jpg. I don't like this solution. It makes the file system way complicated. or I can user PHP's readfile() function or maybe something similar in Perl or Python. For instance I could pass a password using an md5 string to validate visitors as loggedin users with access to that image. I'm leaning towards option 3 but with a Perl or Python angle (assuming they would be faster than PHP). However I would like to see other ideas on the matter. Maybe there is a simple .htaccess trick to this? Basically all I want to make sure is that no one can view images from my website unless the images are directly called from within htmls hosted on my site. Thanks a lot, Haluk

Original source