Image display permissions in PHP / Apache
I have a PHP site with a login system and I am trying to create a function where only specific usernames can view certain images. I think I am trying to do more than just change the .htaccess file because: a) it won't help distinguish between users who are not allowed to view the image, and b) if someone enters the exact url of the image ( "directory/images/photos/230ru0q0238rn230nd_asdi0nqn8.jpg"
), they can still view the image (since it's a physical file in a directory, not text in a DB, etc.). Again, restricting via .htaccess would restrict the entire directory or all files in it, so I can't figure out how it would work. Ideally all images will be blocked trying to access them directly through their direct url and the image will only show between tags<img>
if the user session / username is valid, otherwise they will get an error.
I've heard the term ACL, but I'm not sure if it has anything to do with what I'm trying to do.
a source to share
The authorization scheme and ACL may be different, but to achieve the main purpose of your question:
- Place the images in a non-webpage directory that PHP can read without reading.
- Use
.htaccess
to rewrite all requests to the script (this may eliminate the previous step if it denies direct file access). - Confirm that the requesting user can view the requested image.
- Use
readfile()
(or many other functions) to display the image .
a source to share
What you can do is create a simple context that outputs the image as a stream. The image that is displayed depends on an identifier (or some identifier), for example:
viewImages.php?imageId=234643
viewImages.php checks if the user is logged in / logged in (via $ _SESSION) and if so it sends the image to the browser using readfile
.
a source to share