php restrict access to files in directory

后端 未结 2 1078
予麋鹿
予麋鹿 2020-12-05 22:10

I am trying to restrict direct access to files in a directory. So for example i have website.com/files/example.flv.

So if users go straight to the file in the URL,

相关标签:
2条回答
  • 2020-12-05 22:35

    If you want to restrict access to files, you should consider storing them outside the public DocumentRoot and using PHP to deliver the file, applying your own access logic. This means outside the www or public_html folders, depending on the hosting environment you are working with.

    <?php
    
    // Suppose your "public_html" folder is .
    $file = './../data/test.gif';
    $userCanDownloadThisFile = false; // apply your logic here
    
    if (file_exists($file) && $userCanDownloadThisFile) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename=filename.gif');
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        ob_clean();
        flush();
        readfile($file);
    }
    
    0 讨论(0)
  • 2020-12-05 22:37

    Yes. You'd have to place the files in a directory that's not accessible through the web. Then, you'd have to create a .htaccess file in your public_html/files/ folder, which points to your php script.

    Something like this (note: code not tested):

    Structure:

    • root/
      • realfiles/
      • public_html/
        • files/
          • .htaccess
        • filehandler.php

    .htaccess:

    RewriteEngine on
    RewriteRule ^/files/(.+)$ filehandler.php?stuff=$1 [QSA]
    

    filehandler.php:

    header('Location: /');
    

    Of course you'd want the files to be accessible when you want them to access them. This can be done in filehandler.php, by checking if the user is allowed to view the file, and then returning something like:

    header('Content-type: application/octet-stream');
    header('Content-Disposition: inline; filename="'.basename(urlencode($file['name'])).'"');
    readfile($dir.basename($file['filename']));
    exit;
    
    0 讨论(0)
提交回复
热议问题