【发布时间】:2011-11-17 15:40:39
【问题描述】:
我正在尝试向网站上的授权用户提供 .pdf 和 .doc 文件。用户只有在登录时才能看到文件选择页面,但这并不能阻止未经授权的用户在知道完整 URL 的情况下查看文档。
如何防止未经授权的用户访问这些文件?
【问题讨论】:
标签: php pdf download access-control
我正在尝试向网站上的授权用户提供 .pdf 和 .doc 文件。用户只有在登录时才能看到文件选择页面,但这并不能阻止未经授权的用户在知道完整 URL 的情况下查看文档。
如何防止未经授权的用户访问这些文件?
【问题讨论】:
标签: php pdf download access-control
答案很简单, @Jonnix 在我打字的时候发布了这个,但我会为你解释更多
如果您无法做到这一点,可以将您的文件放在公共 HTML 目录之外,请查看@Andri 的替代答案
E.G cpanel 设置
user/public_html
/public_html/download.php
user/documents/
/documents/file.doc
/documents/file.pdf
@dhh 发布了一个基本的download.php php 文件,但是由于您想强制下载他们的东西,您可以在这里找到并提供正确的 mime 类型,这是对他的代码的扩展,作为 1 强制的最佳方式下载一个文件,2个允许不同的文件类型
download.php
//check users is loged in and valid for download if not redirect them out
// YOU NEED TO ADD CODE HERE FOR THAT CHECK
// array of support file types for download script and there mimetype
$mimeTypes = array(
'doc' => 'application/msword',
'pdf' => 'application/pdf',
);
// set the file here (best of using a $_GET[])
$file = "../documents/file.doc";
// gets the extension of the file to be loaded for searching array above
$ext = explode('.', $file);
$ext = end($ext);
// gets the file name to send to the browser to force download of file
$fileName = explode("/", $file);
$fileName = end($fileName);
// opens the file for reading and sends headers to browser
$fp = fopen($file,"r") ;
header("Content-Type: ".$mimeTypes[$ext]);
// this header tells the browser this is a download and not to try and render if it is able to E.G images
header('Content-Disposition: attachment; filename="'.$fileName.'"');
// reads file and send the raw code to browser
while (! feof($fp)) {
$buff = fread($fp,4096);
echo $buff;
}
// closes file after whe have finished reading it
fclose($fp);
P.S 如果您想添加对其他文件的支持,这里有一个很大的 mime 类型列表 https://www.freeformatter.com/mime-types-list.html
【讨论】:
这为我完成了这项工作:我在我的 apache 网络服务器上的一个普通文件夹(我将其命名为“docs”)中放置了一个 .pdf 和一个 .htaccess 文件,其中包含以下代码。
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
<Files /index.php>
Order Allow,Deny
Allow from all
</Files>
然后我从上面的 Martin Barkers 答案中获取代码,将文件路径更改为“docs/sample.pdf”,并将其粘贴到我的根目录中的 .php 文件中。而已。您现在无法访问每个 url 的文件,但如果您运行 test.php,您可以下载它。
【讨论】:
您应该将所有下载存储在您的公共/用户可访问的文档根目录之外(当然是在您的 basedir 中),并添加一个下载脚本以在用户获得授权的情况下发送下载。
下面是一些如何“发送”文件以进行下载的示例。
$file = "ireland.jpg";
$fp = fopen($file,"r") ;
header("Content-Type: image/jpeg");
while (! feof($fp)) {
$buff = fread($fp,4096);
print $buff;
}
【讨论】:
您可以做的是为文件提供相当于 PHP 代理的功能。
将文件放在 webroot 之外,然后编写一个脚本来检查用户是否允许访问。如果没有,则重定向它们,如果有,则设置适当的标题并输出文件数据。
【讨论】: