php link to image file outside default web directory

It is not possible to directly access files outside of the webroot; this is a builtin security restriction that is there for good reason.

It is however possible to use a PHP-script to serve these images for you. This way you can call an image like:

/image.php?file=myfile.jpg

and use file_get_contents() to get the file contents and print them to your browser. You should also send the headers to the client, in this case using PHP’s header() function. A short example:

<?php

    $file = basename(urldecode($_GET['file']));
    $fileDir="/path/to/files/";

    if (file_exists($fileDir . $file))
    {
        // Note: You should probably do some more checks 
        // on the filetype, size, etc.
        $contents = file_get_contents($fileDir . $file);

        // Note: You should probably implement some kind 
        // of check on filetype
        header('Content-type: image/jpeg');

        echo $contents;
    }

?>

Using a script to this has some more advantages:

  • You can track your downloads and implement a counter, for example
  • You can restrict files to authenticated users
  • … etc

Leave a Comment