Performance-oriented way to protect files on PHP level?

前端 未结 8 528
孤独总比滥情好
孤独总比滥情好 2020-12-09 23:15

I am looking for some input on something I have been thinking about for a long time. It is a very general problem, maybe there are solutions out there I haven\'t thought of

8条回答
  •  旧时难觅i
    2020-12-09 23:51

    Use X-Sendfile

    The best and most efficient way is using X-Sendfile. However, before using X-Sendfile you will need to install and configure it on your webserver.

    The method on how to do this will depend on the web server you are using, so look up instructions for your specific server. It should only be a few steps to implement. Once implemented don't forget to restart your web server.

    Once X-Sendfile has been installed, your PHP script will simply need to check for a logged in user and then supply the file. A very simple example using Sessions can be seen below:

    session_start();
    
    if (empty($_SESSION['user_id'])){
        exit;
    }
    
    
    $file = "/path/to/secret/file.zip";
    $download_name = basename($file);
    
    header("X-Sendfile: $file");
    header("Content-type: application/octet-stream");
    header('Content-Disposition: attachment; filename="' . $download_name . '"');
    

    Important note:

    If you are wanting to serve the file from another webpage such as an image src value you will need to make sure you sanitize your filename. You do not want anyone overriding your script and using ".." etc. to access any file on your system.

    Therefore, if you have code that looks like this:

    Then you will want to do something like this:

    session_start();
    
    if (empty($_SESSION['user_id'])){
        exit;
    }
    
    $file = preg_replace('/[^-a-zA-Z0-9_\.]/', '', $_GET['file']);
    $download_name = basename($file);
    
    header("X-Sendfile: $file");
    header("Content-type: application/octet-stream");
    header('Content-Disposition: attachment; filename="' . $download_name . '"');
    

提交回复
热议问题