php restrict access to files in directory

后端 未结 2 1088
予麋鹿
予麋鹿 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: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;
    

提交回复
热议问题