This question already has an answer here:
Okay, so I'm not so experienced with PHP, and I've been searching for hours for a way to access an image file outside of the document root. I know there are many answers to this question, sort of, but none that actually helped me.
So what I have so far is a folder structure like this (ignore the odd file names):
-img
-imagez.php
-logo.php
-public_html
-files.php
I put this code inside of files.php
:
<?php include('/home/byonexco/img/imagez.php'); ?>
If I access files.php
from my browser, I see the content of imagez.php
, as is expected.
My problem is, I want to be able to do the same thing with the file logo.png
. The folder img
is not publicly accessible, so I know I have to call the image with PHP.
How can I get logo.png
to show on the page when someone accesses the file files.php
?
</div>
You could write a very simple script like
<?php
header('Content-Type: image/png');
if (strpos($_GET['img'], '..') === false) // check for quackery
readfile('../img/' . $_GET['img']);
and access it like
/img.php?img=logo.png
However there are a couple disadvantages to this solution:
You're far better off with hosting images directly accessible.
As the image isn't publicly accessible, you'd need to get the image via PHP then output the image with the correct header
$image = file_get_contents('path/to/image.png';
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);