Creating a private image folder?

2019-08-01 07:26发布

问题:

I have a growing website with around 30k images in 4 sizes for a total of 120k. My current solution is storing them in a DB and from what I've read on stack oveflow this seems to be a very bad idea.

I'm starting to see why. I've noticed a drastic decrease in performance. think the obvious solution is to move these images to a folder setup and I'd like to use the users ID as a dir name and then have a public and private sub dir.

The structure would look like this:

/54869
    /public
        /size_1/img1.jpg
        /size_2/img1.jpg
        /size_3/img1.jpg
        /size_4/img1.jpg
    /private
        /size_1/img2.jpg
        /size_2/img2.jpg
        /size_3/img2.jpg
        /size_4/img2.jpg

What is the best way to secure this private folder and only provide other users access if the owner of the file has granted permission?

I'd also like to prevent users from simply viewing the contents of any folder but I suppose I could perform a check client side to fix this.

Any thoughts or suggestions?

回答1:

You could make that folder not accessible from the web (e.g. place the folder outside htdocs or add .htaccess rules).

Create a PHP script which handles all requests to the private images. This script would have to do the following:

  • check if the user is authenticated
  • check if the user is authorized to view the requested image
  • open the image and print it to the browser (you need to set correct http headers to make sure the content is treated as an image)

Then, in your HTML, simply point to /secret_image.php?id=3 or maybe you want to use the path of the image /secret_image.php?p=/54869/public/size_1/img1.jpg



回答2:

You can try this

imageViewer.php?imgID=XXX;     where XXX=hashFunction(salt.imgName)

And do all the processing in the imageViewer.php like if the user has permission or not !