How to serve documents from outside the network via PHP?

For security, I move the collection of files and folders outside the root web server on the Apache server, and then I will serve them dynamically. This seems to be better than 2 alternative:

  • Leave them available on the Internet and just create a php login page that is added to each file. The problem is that these are not all php files, and I cannot add the php input file to pdf, image, etc.
  • Leave them available online and use HTTP authentication to restrict access to the entire directory. But this introduces problems, including cleartext passwords, lack of an elegant exit method, etc.

So, we returned to the fact that they were outside the root website, but served them dynamically. The problem I encountered is different types of files (php scripts, txt, pdf, jpg). I am not sure whether to use include() or readfile() . And I am having problems sending the appropriate headers for each file so that the browser displays them correctly.

Did I miss another magic solution? Is there some kind of infrastructure that has eluded me that handles the flow of dynamic files and headers?

(FYI I use Linux, Apache and PHP on a shared host)

+7
source share
2 answers

I think something like this will 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); 
+8
source

The easiest way I can think of is to use .htaccess files. Assuming your Apache web server, of course.

You can restrict access to all types of files and / or directories for everyone and allow only localhost. Thus, they will not be available to the public, even if they know the correct path / url, but the server and PHP will be able to serve them.

There must be equivalent solutions for different web servers. In addition, you can always switch to Apache :-)

0
source

All Articles