我正在尝试向网站上的授权用户提供 .pdf
和 .doc
文件。用户在登录后只能看到文件选择页面,但这并不能阻止未经授权的用户在知道完整 URL 的情况下查看文档。
如何防止未经授权的用户访问这些文件?
最佳答案
答案很简单, @Jonnix 在我打字时发布了这个,但我会为你解释更多
如果您无法做到这一点,请将您的文件放在公共(public) HTML 目录之外,看看@Andri 的替代答案
E.G 控制面板设置
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
关于PHP保护PDF和DOC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7427457/