Retrieve files from outside wwwroot

Discussions of secure PHP coding. Security in software is important, so don't be afraid to ask. And when answering: be anal. Nitpick. No security vulnerability is too small.

Moderator: General Moderators

Post Reply
espenbe
Forum Newbie
Posts: 2
Joined: Fri Sep 18, 2009 3:25 pm

Retrieve files from outside wwwroot

Post by espenbe »

Hi
How can I retrieve files (images) from a directory outside wwwroot and display them on a web-site using a PHP-script? I've seen lots of examples of using the "header"-directive, but I want the image to be embedded in a website. The purpose is to avoid people to enter the picture-URL in the web-browser and mass-download pictures. Any suggestions or pointers are welcomed

Example:
wwwroot: /local/www/
Image-dir: /local/images/
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Retrieve files from outside wwwroot

Post by John Cartwright »

Using header() to output the appropriate content headers, and a simple readfile() which accepts the full path to your files (assuming PHP can access them). There are a ton of examples in the comments of those two links.

You would then reference your script as a normal image, something like:

Code: Select all

<img src="/path/to/your/script.php?file=file1.jpg">
User avatar
kaisellgren
DevNet Resident
Posts: 1675
Joined: Sat Jan 07, 2006 5:52 am
Location: Lahti, Finland.

Re: Retrieve files from outside wwwroot

Post by kaisellgren »

espenbe wrote:The purpose is to avoid people to enter the picture-URL in the web-browser and mass-download pictures.
You would need to have some sort of authentication (e.g. use PHP sessions and a simple login system) to prevent direct downloads from random visitors. If you want to prevent one user from downloading multiple images, you need to set some kind of counter for each user who has logged in so that they are limited to download too many pictures. If you don't want to limit that, but stop spam, then you could setup some kind of tokens in order to view images.
espenbe
Forum Newbie
Posts: 2
Joined: Fri Sep 18, 2009 3:25 pm

Re: Retrieve files from outside wwwroot

Post by espenbe »

John: your suggestion worked very well, and I think I will stick to that one for a while. Thank you very much :)

kaisellgren: Thank you for valuable thoughts and ideas which I will try to follow up at a later stage.
Post Reply