htaccess - 禁止直接访问除登录用户以外的所有文件(PHP)

时间:2016-10-26 10:05:41

标签: php .htaccess

使用.htacess(全部拒绝) - 是否可以只允许登录系统的用户直接访问文件?如果它有任何区别我的网站是用Drupal(PHP)构建的。如果这是可能的,那么理想情况下我也希望检查用户的角色。

1 个答案:

答案 0 :(得分:2)

单独使用.htaccess无法执行此操作。你需要做的是:

  1. 拒绝所有
  2. 的文件访问权限
  3. 拥有一个“文件提供程序”脚本,允许在身份验证后进行文件直通。
  4. 示例:

    <强> proxy.php

    <?php 
    $proxiedDirectory = "./files/"; //Whatever the directory you blocked access to is.
    $filename = isset($_GET["fn"])?$_GET["fn"]:null;
    
    if ($filename === null || !file_exists($proxiedDirectory.$filename)) {
        http_response_code(404);
        exit;
    }
    
    if (!user_is_authenticated()) { //Not a real method, use your own check
        http_response_code(403);
        exit;
    }
    
    
    $fp = fopen($proxiedDirectory.$filename, 'rb');
    
    header("Content-Type: image/???"); //May need to determine mime type somehow
    header("Content-Length: " . filesize($proxiedDirectory.$filename));
    
    fpassthru($fp);
    exit;
    

    你可以通过以下方式使用:

    http://example.com/proxy.php?fn=filename.txt