0

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?

MyNameWouldGoHere
  • 145
  • 1
  • 2
  • 13

2 Answers2

0

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);
user3791372
  • 4,445
  • 6
  • 44
  • 78
0

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:

  • Relaying the image through PHP costs time and performance
  • The script is possibly subjectible to exploits, letting an evil person retrieve any file on the server

You're far better off with hosting images directly accessible.

Cobra_Fast
  • 15,671
  • 8
  • 57
  • 102
  • 1
    This is a VERY bad idea. Allowing filenames to be specified in the request without parsing / sanity checks is VERY dangerous. Do not do this. – user3791372 Aug 06 '14 at 21:29
  • @user3791372 which is why i wrote the disclaimer. But fair enough, I've added a very crude check. – Cobra_Fast Aug 06 '14 at 21:31
  • `/img.php?img=/..` will bypass that no? – user3791372 Aug 06 '14 at 21:33
  • @user3791372 No it won't. The condition fails as soon as `..` appears anywhere in the string and we're still prepending `../img/`, so an absolute path won't work either. – Cobra_Fast Aug 06 '14 at 21:35
  • Thing is though, I can't access (for some weird reason) the img folder with PHP by using ../ That's why I was looking for other solutions. I want to be able to stop users who aren't logged in from accessing certain images – MyNameWouldGoHere Aug 06 '14 at 21:35
  • @user3779981 In that case your OpenBasedir setting may not allow file access outside of your webroot. Check for that. – Cobra_Fast Aug 06 '14 at 21:36