我正在尝试在网站上为授权用户提供
我该如何防止未经授权的用户访问这些文件?
.pdf
和.doc
文件。用户只有在登录时才能看到文件选择页面,但这并不能防止未经授权的用户查看文档,如果他们知道完整的URL。我该如何防止未经授权的用户访问这些文件?
.pdf
和.doc
文件。用户只有在登录时才能看到文件选择页面,但这并不能防止未经授权的用户查看文档,如果他们知道完整的URL。user/public_html
/public_html/download.php
user/documents/
/documents/file.doc
/documents/file.pdf
download.php
php文件,但是由于你想要强制下载他们的东西,您可以像在这里找到和提供正确的mime类型一样。以下是对他的代码的扩展,以实现1文件的强制下载和2允许不同的文件类型。//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
您应该将所有下载内容存储在公共/用户可访问的文档根目录之外(当然,在基目录内),并添加一个下载脚本以在用户经过授权后发送下载。
以下是如何“发送”文件以进行下载的示例。
$file = "ireland.jpg";
$fp = fopen($file,"r") ;
header("Content-Type: image/jpeg");
while (! feof($fp)) {
$buff = fread($fp,4096);
print $buff;
}
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
<Files /index.php>
Order Allow,Deny
Allow from all
</Files>
然后我使用Martin Barker上面的代码,将文件路径更改为“docs/sample.pdf”,并将其粘贴到我的根目录中的.php文件中。就这样。现在您无法通过URL访问该文件,但是如果运行test.php,则可以下载它。