我有一堆文件可供下载,我想通过登录来保护它们并隐藏路径以防止盗链。我正在使用 PHP 脚本来执行此操作(感谢 Mike Zriel 的下载脚本,我只是添加了自己的数据库调用和用户登录检查)。
/**
* Force file download and hide real Path
* @version 11.03.11 March 11, 2011
* @author Mike Zriel, http://www.zriel.com
* @copyright Copyright (C) 2010
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only
* @params
* filePath = Real Path of file
* fileName = File Name
*/
//CHECK USER LOGIN
if(!isset($_COOKIE['login'])) {
echo "You are not authorised to download this file.";
exit;
} else {
include('database_connection.php');
//VALIDATE VARIABLES
if(isset($_GET['fileid'])) {
if(!preg_match("/^\d+$/",$_GET['fileid'])) {
echo "Invalid File ID.";
exit;
}
} else {
echo "No File Specified.";
exit;
}
try {
$sql = $pdo->prepare("SELECT * FROM files WHERE id = ?");
$sql->execute(array($_GET['fileid']));
$array = $sql->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo "Error downloading file: ".$e->getCode();
}
if(!empty($array)) {
$filePath = "http://www.example.com/PathToFile/";
$fileName = $array['path']);
}
if(substr($filePath,-1)!="/") $filePath .= "/";
$pathOnHd = $filePath . $fileName;
if(isset($_GET['debug'])) {
echo "<br />".$pathOnHd;
}
if ($download = fopen ($pathOnHd, "br")) {
$size = filesize($pathOnHd);
$fileInfo = pathinfo($pathOnHd);
$ext = strtolower($fileInfo["extension"]);
switch ($ext) {
case "pdf":
header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename=\"{$fileInfo["basename"]}\"");
break;
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"{$fileInfo["basename"]}\"");
}
header("Content-length: $size");
while(!feof($download)) {
$buffer = fread($download, 2048);
echo $buffer;
}
fclose ($download);
} else {
echo "There was an error accessing the file: ".$array['name'].". <br />";
}
exit;
}
我遇到的问题是对于一些较小的 ZIP 或 PDF 文件(<1MB 左右)这工作正常,但对于一些较大的 ZIP 文件我有(15-20MB)浏览器(在 Chrome 和 Firefox 中测试)抛出一个网络错误并在下载结束时失败。我认为这与这一点有关,但更改缓冲区大小似乎没有任何效果?
while(!feof($download)) {
$buffer = fread($download, 2048);
echo $buffer;
}
任何人都可以发现有什么问题吗?
编辑:从下面的答案中尝试了以下...
readfile($pathOnHd); //Results in Unknown Network Error
while(!feof($download)) {
$buffer = fread($download, 2048);
echo $buffer;
flush();
} //Not using ob_start() so not sure why this would change anything and it doesn't
while (($buffer = fread($download, 2048)) != FALSE) {
echo $buffer;
// Results in Unknown Network Error
}
注意:如果我回显浏览器的路径并将其粘贴为直接链接,则文件下载正常。所以我与 PHP 不喜欢这些较大的文件有关。