Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

restrict access to image files for logged in users only in php

Tags:

php

Suppose user A has some images in his/her account in Facebook which s/he can view after log-in.

If user A logs out and the url of one of those images is tried, 'access restriction '-type message appears.

Think of a social networking site built in PHP.

How to achieve that kind of control so that NO images can be viewed without logging in to the site JUST as Facebook does?

like image 629
Istiaque Ahmed Avatar asked Apr 01 '12 09:04

Istiaque Ahmed


1 Answers

  • Move all of the images to a folder which is not accessible from the web.
  • Implement a php script (image.php) which checks if the user is logged in and accepts an image name as input (e.g. image.php?name=flower.png).
  • If the user is logged in, send the proper content-type image header() http://il2.php.net/manual/en/function.header.php (image/png for example)
  • Read the file from disk and send it to the user using readfile() http://php.net/manual/en/function.readfile.php.
  • Make sure people won't be able to access files outside the images dir by sending something like /images.php?name=/etc/hosts (it would be better to accept an image ID instead of a file name, or a hash of the file name, you can use md5() http://il2.php.net/manual/en/function.md5.php to generate the hash but remember to name the image files according to their md5 hashes, in this case you always lookup the image file only in the images directory).
  • If the user is not logged in, you can send a custom image which reads "please login" or just terminate the script.
like image 177
Yaniro Avatar answered Nov 18 '22 19:11

Yaniro