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

I think something like this would work:

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

$parts = explode("https://stackoverflow.com/", 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);

Leave a Comment