简体   繁体   中英

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

For security I'm moving a collection of files and folders to outside the web root on an apache server, and then I will serve them dynamically. This seems better than 2 alternatives:

  1. Leave them web accessible and just create a php login page that gets prepended to every file. The problem is they're not all php files, and I can't prepend a php login file to a pdf, image, etc.
  2. Leave them web accessible and use HTTP authentication to restrict access to the whole directory. But that introduces problems including cleartext passwords, no graceful logout method, etc.

So we're back to having them outside the web root but serving them dynamically. The problem I'm having is, since they're all different file types (php scripts, txt, pdf, jpg) I'm not sure whether I should use include() or readfile() . And I run into problems with sending the proper headers for every file so that the browser displays them correctly.

Am I missing another magic solution? Is there a framework that has eluded me that handles the serving of dynamic files and headers?

(FYI I'm running Linux, Apache & PHP on a shared host)

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);

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 :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM