Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use htaccess to validate with php before granting access to a directory

I'm working on an app where users can create an account and upload images, which get stored in a directory and can then be displayed within the application itself or in a publicly visible part of the app. Now I'd really like to protect the images to ONLY allow access to these images in the event that certain conditions are met, i.e, a session is set or the permissions in the db for the image are set to public, to name a few.

So, what I'd need is that whenever an image from that directory is loaded, the htaccess file passes the image name onto a php file in that directory, which runs whatever checks it has to, and if it returns true, htaccess can proceed with spitting out the image (whether it's in an tag or just entered in the address bar of the browser).

I've trolled through many posts but haven't found anything. I can't imagine it's not possible, so anyone who can offer guidance will be prayed for - and if you're local, well, other benefits may be in store!

like image 440
Meezaan-ud-Din Avatar asked Feb 23 '23 11:02

Meezaan-ud-Din


1 Answers

Store the uploaded images in a non web-accessible folder, then Use a rewrite rule to forward requests to php; Something like: RewriteRule ^images/([^/]+) /image.php?img=$1 [NC]

Do your validations in the php and if ok forward the image from the non-readable folder via php; something like

header('Content-type: '.$mime);
header('Content-length: '.filesize($filename));
$file = @ fopen($filename, 'rb');
if ($file) {
  fpassthru($file);
  exit;
}
like image 152
PtPazuzu Avatar answered Feb 26 '23 01:02

PtPazuzu