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

Chr*_*ris 2 php .htaccess

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

apo*_*fos 5

你无法.htaccess独自做到这一点。你需要做的是:

  1. 拒绝所有文件访问
  2. 有一个“文件提供程序”脚本,允许在身份验证后通过文件。

例子:

代理.php

<?php 
$proxiedDirectory = "./files/"; //Whatever the directory you blocked access to is.
$filename = isset($_GET["fn"])?$_GET["fn"]:null;

if (!user_is_authenticated()) { //Not a real method, use your own check
    http_response_code(403);
    exit;
}

if ($filename === null || !file_exists($proxiedDirectory.$filename)) {
    http_response_code(404);
    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;
Run Code Online (Sandbox Code Playgroud)

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

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