受 PHP 保护的文件访问


PHP protected file access

我几乎逐字使用马丁·巴克的代码/答案(PHP来保护PDF和DOC),唯一的区别是我保护的文件位于public_html文件夹上方的用户文件夹中

文件夹结构

/users/websupport
/public_html

要下载的文件位于:

/users/websupport/FileToDownload.pdf

下载.php文件位于

/public_html/download.php
但是Firefox告诉我它找不到文件在

Firefox找不到文件在下载.php时找不到文件。

我已经通过 ftp 验证了该文件。

如果将文件放在 webroot 之外,我需要向网站添加一些东西吗 .htaccess ?只是不知道我哪里出了问题。以下是下载中的代码.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 = "../users/websupport/2011cv.pdf";
// 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]);
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);

确保 php 脚本运行的用户对该目录具有读取访问权限。

大多数 debian 衍生产品上嵌入在 apache 中的 php 上,用户将是"www-data"。

我最近遇到了同样的问题,readfile() 和 fpassthru() 在我的服务器上不起作用。

我最终所做的是根据需要为文件创建符号链接并将其传递给用户。您可以在此处了解如何创建符号链接。

我用了

exec("ln -s source_file_full_path full_path_to_fake_file");

如果您希望您的用户有一个像"http://somesite.com/folder/fake_file.pdf"这样的链接,那么完整路径将是"文件夹"在您的服务器上所在的位置,您将在假文件路径中包含"fake_file.pdf"。

然后为了使链接过期,我再次调用以查找创建日期早于 x 分钟的所有符号链接。您可以在此答案中看到如何做到这一点。(这可能是一个 cron 作业,以确保它们按时过期。