Managing access to graphics using .htaccess and mod_rewrite

trippy1976 used Ask the Experts™
I have a directory of graphics that I now want to manage access to.

In the past, I have linked to the graphics like this:

Each graphic is called "image.jpg" and resides in a directory named by the graphic ID, in the example above 19002

Now, if the user of 19002 set permissions to "not public" it still serves it up.  

So what I want is a quick PHP script that when someone links to the graphic like above, it is actually being served by:

Which will then check the permissions for that graphic and either serve it back or serve back a default "private" graphic.

I think I should be able to do this with mod_rewrite but despite googling and reading and tinkering for a few hours I can't get it to work.  Hoping someone here can give me a quick example.  Here was my latest attempt:

Options +FollowSymlinks
RewriteEngine on
RewriteRule ^thesegraphics/([0-9]+)/image.jpg$1 [NC]

Open in new window

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^images/thesegraphics/([0-9]+)/image.jpg$1 [L,QSA]

Open in new window


Thank you!

Is there any way to do it so that people don't realize (i.e. the URL stays the same)

would still show up in my browser.
yes it's possible, with the above .htaccess file.

create file in script and call it getimg.php, then paste following code:
$file = realpath("images/thesegraphics/{$_GET['id']}/image.jpg");

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));

Open in new window

should work. read here for more info
Top Expert 2004

>>> (i.e. the URL stays the same)

If you remove the protocol and host from the destination, you ake it a rewrite, instead of a redirect:

RewriteRule ^images/thesegraphics/([0-9]+)/image.jpg /scripts/getimg.php?id=$1 [L,QSA]

Open in new window


routinet:  Thank you for the information.  I actually discovered this on accident.  It also makes the re-write compatible accross domains which is important for me (I do testing on test. and prod is www. so not having a hard coded domain name makes the .htaccess file portable)

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial