How to serve documents from outside the web root using PHP?

Solution 1:

I think something like this would work:

<?php
$path = realpath(dirname(__FILE__) . '/../my_files/' . $_GET['file']);

$parts = explode('/', pathinfo($path, PATHINFO_DIRNAME));
if (end($parts) !== 'my_files') {
    // LFI attempt
    exit();
}

if (!is_file($path)) {
    // file does not exist
    exit();
}

header('Content-Type: ' . mime_content_type($path));
header('Content-Length: ' . filesize($path));

readfile($path);

Solution 2:

The simplest way I can think of is by using .htaccess files. Assuming your web server is Apache, of course.

You could deny access to any kind(s) of files and/or directories for everyone and allow only for localhost. This way, they will not be served to the public, even if they know the correct path/url, but the server and PHP will be able to serve them.

For different web servers, there must be equivalent solutions. Plus, you can always switch to Apache :-)