这个问题在这里已有答案:
我想在一个文件夹中构建一个受保护数据的网站。我在我的PHP中有一个会话检查,仅在登录时显示数据。
数据是一对.PDF和.JPG文件。
但是当一个nog登录用户完成url搜索时,他可以找到并打开文件。示例:www.domain.com/protected-data/file.pdf
我该如何保护?
我已经用.htaccess做了一些技巧。
Order Allow,Deny
Allow from all
<Files ~ "\.(gif|jpg|png|pdf)$">
Deny from all
</Files>
但即使用户登录,此脚本也会拒绝我的所有文件。
我们的想法是将您的文件放在外部无法使用的目录中。假设您有以下目录结构:
|_src
\_.htaccess
|_private
\_.htaccess
|_public
\_read.php
src /:包含您的类,源代码。 private /:包含您的JPG和PDF文件。 public /:包含您的前端控制器,这是Internet上唯一可用的直接控制器。
SRC /的.htaccess
# No one should be able to access your source code from Internet
Deny from All
民营/的.htaccess
# No one should be able to access your private files from Internet
Deny from All
这样做只能从Internet访问公共/目录。在您的公共/目录中,您可能有一个读取这些文件的PHP文件。这是一个小例子。
公共/ read.php
<?php
session_start();
//if the user is logged, read the file and echo it
if (1 === $_SESSION['logged']) {
//Filename to read could be given like ?file=invoice.pdf
$file = $_GET['file'];
//Warning: you should sanitize the $file to prevent an attacker to give a file like "../src/yourclass.php".
echo file_get_contents(__DIR__.'/../private/'$file);
}
关于Deny,请参阅Apache documentation。