Manu
Manu

Reputation: 263

How can i show the images outside the web root directory in my php application?

I have web application in PHP using apache server, linux. For some security reason i am keeping the documents and images outside web root. How can i show these images, when the user login.

Upvotes: 10

Views: 16818

Answers (4)

Legionar
Legionar

Reputation: 7607

Inside your www directory, create a "image.php" file, with a similar content to:

<?php
header('Content-Type: image/png');
readfile("../img/" . basename($_GET['img']));

And call your images with

<img src="image.php?img=myimage.png" />

Please be aware that your PHP file shouldn't be that simple :) As you may want to address multiple image formats (and providing the correct header for them), checking for malicious file path/inclusions (you don't want to use $_GET without validating/sanitizing the input), extra caching etc. etc. etc.

But this should give you an idea on how you can target your issue.

Upvotes: 13

Thomas Nordquist
Thomas Nordquist

Reputation: 643

As simple as that, this will output the image with correct headers,
remember that you have to set the header() before flushing anything out of the output buffer
=> no echo or print before

$file = '../../somedirectory/image.jpg';
header('Content-Type:image/jpeg');
header('Content-Length: '.filesize($file));
echo file_get_contents($file);

Upvotes: 4

Healyhatman
Healyhatman

Reputation: 1659

For my application, none of those answers were working - I simply couldn't get the image to display and it wasn't really feasible for me to add a new php file to call because reasons. What DID work for me is

$filename = read_filename_from_database;
$fileDir = "/path/to/files/";
$file = $fileDir . $filename;
if (file_exists($file))
{
     $b64image = base64_encode(file_get_contents($file));
     echo "<img src = 'data:image/png;base64,$b64image'>";
}

Upvotes: 9

Tijo John
Tijo John

Reputation: 622

use the ob_clean() function of php before the readfile()

it will usefull to avoid space like issues

Upvotes: 0

Related Questions