Page 1 of 1

Accessing files outside the web root

Posted: Mon Dec 13, 2010 9:59 am
by social_experiment
I want to access files outside the root of my website but don't know how to go about it. The folder is called img so i created the following script:

Code: Select all

<?php
 // this is an example, don't critique me 
 // on this.
$uploaddir = '/img/';
$name = '1.png';
	
echo '<img src="'. $uploaddir/$name .'" width="50" 
height="50" border="50" />';

echo '<br />';	
readfile($uploaddir.$name);
?>
I tried both readfile() and the img HTML tag but neither will display the image. Readfile does give an error indicating that is no such directory.

1. What would be the correct syntax to access a file outside the root folder (public_html)?

My hosting provider says it is possible using a php script and I'm thinking he is refering to this.

Re: Accessing files outside the web root

Posted: Mon Dec 13, 2010 11:00 am
by AbraCadaver
Depends on where the directory is located. Try using the full path to the directory, like /home/somebody/img.

Re: Accessing files outside the web root

Posted: Mon Dec 13, 2010 12:26 pm
by social_experiment
I changed $uploaddir to the following '../../img/' . Now readfile() spits out a ton of weird data, im assuming it has found the file (and it's not giving an error message anymore). Yet when i try to display the file with an img HTML tag, it still doesn't show the image. Is the IMG tag the correct way to display the image in this case?

Re: Accessing files outside the web root

Posted: Mon Dec 13, 2010 12:58 pm
by AbraCadaver
social_experiment wrote:I changed $uploaddir to the following '../../img/' . Now readfile() spits out a ton of weird data, im assuming it has found the file (and it's not giving an error message anymore). Yet when i try to display the file with an img HTML tag, it still doesn't show the image. Is the IMG tag the correct way to display the image in this case?
If the image is outside of the web root then the img tag will not display it because the image is not accessible. readfile() may work but you have to send the proper headers (content type, length, etc.).

Re: Accessing files outside the web root

Posted: Tue Dec 14, 2010 4:05 am
by social_experiment
AbraCadaver wrote:readfile() may work but you have to send the proper headers (content type, length, etc.).
It does indeed work, but it makes it difficult to include this image ,lets say use the image as a profile photo. The header('Content-Type: image/jpeg') seems to block any other text that you might want to display.

Re: Accessing files outside the web root

Posted: Tue Dec 14, 2010 8:35 am
by AbraCadaver
You need to display the image in a PHP file and then have this file as the src of an img tag. Here is something similar just with an image from a database: viewtopic.php?f=1&t=110171&p=582727#p582727

Re: Accessing files outside the web root

Posted: Tue Dec 14, 2010 10:24 am
by social_experiment
Cool :). Thanks for the help on this.