PHP保护PDF和DOC文件

5
我正在尝试在网站上为授权用户提供.pdf.doc文件。用户只有在登录时才能看到文件选择页面,但这并不能防止未经授权的用户查看文档,如果他们知道完整的URL。
我该如何防止未经授权的用户访问这些文件?
4个回答

8
答案很简单,当你无法将文件放在公共HTML目录之外时,请参考@Andri的答案提供的替代方法。
例如:cpanel设置。
user/public_html
    /public_html/download.php

user/documents/
    /documents/file.doc
    /documents/file.pdf

@dhh发布了一个基本的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


3

您应该将所有下载内容存储在公共/用户可访问的文档根目录之外(当然,在基目录内),并添加一个下载脚本以在用户经过授权后发送下载。

以下是如何“发送”文件以进行下载的示例。

$file = "ireland.jpg";
$fp = fopen($file,"r") ;
header("Content-Type: image/jpeg");

while (! feof($fp)) {
    $buff = fread($fp,4096);
    print $buff;
}

3
你可以提供相当于PHP代理的等效内容来处理这些文件。
把文件放在网站根目录之外,然后编写一个脚本来检查用户是否有权限访问。如果没有权限,则重定向用户;如果有权限,则设置适当的标题并输出文件数据。

1
这对我有用:我在我的Apache Web服务器上的一个普通文件夹中放置了一个.pdf和一个.htaccess文件,并在其中放置了以下代码。我将其命名为“docs”。
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,则可以下载它。


2
如果您没有Web服务器用户目录的支持,例如您只能访问public_html目录而无法访问上层目录(一些免费主机提供此类服务),那么这是一个好主意。 - Barkermn01

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接