phpdocument-root

Access a file which is located before / outside the server root directory?


I'm making an intranet for a post-sale customer service entreprise. Employee need to be able to upload img files to the intranet's server and i need to store them in a directory with is BEFORE www (the website's root directory).

Doing this using php is pretty easy but how to include these imgs on the website once they're uploaded ? I tried this code

<img src="../img/img.png"/>

This is not working because i can't send a file if it is OUTSIDE the server's www directory ...

Is there any proper way to do that ?

Current treeview :

server root directory
           |www
               |(all server files)
           |img
               |(all img files)

(the server's index.php is located in www and the files are in img)


Solution

  • You cannot directly access any file outside your web directory. As your question includes the tag PHP as well, I assume you may want to use it.

    What you can do is the following:

    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.