2

Background:

  • I have a folder with images called uploads or images located outside the website root. ( outside of public_html )
  • I am trying to print the image inside let's say image.php.

Rules for doing it:

  • I am trying to do it without using alias mod_rewrite in .htaccess.
  • Without showing a black background and image in the middle ( I don't want it like when browsing domain.com/image.png. like the example of the picture I mentioned below.
  • Without using another page and pass it as get.

What I tried:

  • I checked many questions, one of them is this and another is this.
  • From following the current questions asked above and other tutorials, I came up with this:

    <?php
    
    $location = dirname($_SERVER['DOCUMENT_ROOT']);
    $image    = $location . '/public_html/images/banned.png';
    
    header('Content-Type:image/png');
    header('Content-Length: ' . filesize($image));
    echo file_get_contents($image);
    
    ?>
    
    <img src=" <? echo $image; ?> "/>
    

It works fine, and here is an example:

Gyazo


However, this is not what I am looking for, or trying to do. Again, I am trying to view it as a normal image src as it will be used for a profile picture or other usages.

Any help will be much appreciated. Thanks in advance!

Mr Pro Pop
  • 666
  • 5
  • 19

2 Answers2

2

This:

echo file_get_contents($image);
?>

<img src=" <? echo $image; ?> "/>

is wrong for a few reasons. First, you cannot mix raw image content with HTML markup that way. Also src specifies the URL of the image not the raw content.

You can either move your echo file_get_contents($image); and related code to separate file, i.e. image.php, then reference it in your src, passing image name as argument (i.e. image.php?img=foo.jpg) - note that if you do this wrong, you will be open to directory traversal attack). Alternatively you can try to use rectory traversal attackdata URI scheme as src argument and pass raw content directly that way.

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
2

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(); ?>' >
Pang
  • 9,564
  • 146
  • 81
  • 122
rndus2r
  • 496
  • 4
  • 17