PHP保护PDF和DOC

标签 php pdf download access-control

我正在尝试向网站上的授权用户提供 .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/

相关文章:

java - 从 Java 中静默打印 PDF

.net - 在 .net 网站中生成文本文件的最佳方法是什么?

PHP:线程代理共享一个公共(public)对象

c++ - 是否有 C++ 库可以从 PDF 文件(如 Java 的 PDFBox)中提取文本?

java - 如何使用 iText 获取段落绝对坐标?

java - 下载大小大于可用流/文件大小。 (阿莎 501,J2ME)

快速保存下载的视频 NSURLSession

php - 如何在php中获取前3个月的数据

可以使用 Netbeans + PHPUnit 在远程服务器上进行 PHP 单元测试吗?

php - MySQL - 将行从一个表移动到另一个表但使用新 ID