开发者

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!


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;
}


If I were you I would move all of your images to a certain folder and then build a php script like this called image.php:

<?php

// You may want to use image name depending on 
// if you can fetch the name from the db from an id
// You need the filename to open the image later

$iid = 0;
if(isset($_GET['iid']))
    $iid = (int)$_GET['iid'];

// Check session
// Check database permissions ect.

// If you don't want this image to be output call die();

// If it's a go, output the image.

// Change this to the type of the image you're about to output
header('Content-Type: image/png');

readfile('images/'.$image_filename);

?>

You can set up your .htaccess like:

RewriteRule ^images/(.*)$ image.php?iid=$1 [L]

So that when a request is made for images/10.jpg it instead calls your script with iid=10.jpg

You can change your .htaccess a bit, depending on whether you want to use ids or filenames and such, you might not want the .jpg passed along. Same with the script. Let me know if you have any questions :)


As far as I understand your case, you need to close direct access to files by .htaccess

deny from all

and make an PHP front-end in another directory, that will take path or just picture filename from $_GET and check if conditions are met and return image, for example

header("Content-type: image/jpeg");
readfile("/path/to/my/images/$image");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜