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

后端 未结 2 1192
抹茶落季
抹茶落季 2020-11-30 08:09

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 alte

相关标签:
2条回答
  • 2020-11-30 08:44

    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);
    
    0 讨论(0)
  • 2020-11-30 08:47

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

    0 讨论(0)
提交回复
热议问题