PHP Link to Image File Outside Default Web Directory

How to echo image that is outside of the public folder

direct path won't work because you can't get content from outside of root folder.. you can do it another way, Read image file in php script from server dir path and serve file using header

script file.php

<?php
$mime_type = mime_content_type("/image_path/{$_GET['file']}");
header('Content-Type: '.$mime_type);

readfile("/image_path/{$_GET['file']}");
?>

<img src="file.php?file=photo.jpg" />

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

PHP by default can already access files outside the web root, unless restricted with an open_basedir directive (or safe mode, but hope you're not in that cage).

It's normally a good practice to insert within a VirtualHost configuration an open_basedir restriction. You can specify multiple directories separated by : on Linux and ; on windows.

php_admin_value open_basedir /var/www/s/stage:/usr/share/php:/your/dir

To access those files either use an absolute path or a path relative to the position of the PHP file called. (So you'll have to ../ to reach levels above).

Also be sure that directories in which you want to write to are assigned to the webserver user and have write permission.

Otherwise you have second option:

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

<?php
header('Content-Type: image/png');
readfile("../img/" . $_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.

How to use a media file located outside of public folder on a website? (PHP, HTML)

Public media (images, javascript etc.) should be accessible from public directory, but there are solutions to work around this.

You can display PHP code as an image.

Output an Image in PHP

Display image from outside the web root ( public_html )

Change your image.php to

<?php
function image() {
$location = dirname($_SERVER['DOCUMENT_ROOT']);
$image = $location . '/public_html/images/banned.png';

return base64_encode(file_get_contents($image));
}
?>

In another file where you want to display that image, let's say test.php:

<?php
include("image.php");
?>
<img src='data:image/png;base64,<?= image(); ?>' >


Related Topics



Leave a reply



Submit