【发布时间】:2017-03-30 15:19:55
【问题描述】:
我正在使用以下代码隐藏真实文件路径以防止盗链。每当我尝试通过新创建的地址下载文件时,包括文件大小和文件名在内的一切都正常,但是当我尝试打开文件时,无论是 PDF 文件还是 ZIP 文件,它都说文件已损坏.
当我直接从服务器下载文件时,它可以工作并且没有任何问题。
$file = 'file.pdf';
$path = $_SERVER['DOCUMENT_ROOT'].'/files/';
$file_Path = $path . $file;
list($file_Basename, $file_Ext) = explode('.', $file);
switch($file_Ext)
{
case "pdf": $ctype = "application/pdf"; break;
case "exe": $ctype = "application/octet-stream"; break;
case "zip": $ctype = "application/zip"; break;
case "rar": $ctype = "application/rar"; break;
case "doc": $ctype = "application/vnd.ms-word"; break;
case "xls": $ctype = "application/vnd.ms-excel"; break;
case "ppt": $ctype = "application/vnd.ms-powerpoint"; break;
case "gif": $ctype = "image/gif"; break;
case "png": $ctype = "image/png"; break;
default: $ctype = "application/force-download";
}
header('Content-Type:'. $ctype);
header('Content-Length:' . filesize($file_Path));
header('Content-Transfer-Encoding: binary');
header('Content-Disposition: attachment; filename="downloaded.pdf"');
readfile($file_Path);
exit();
我做错了什么?!
【问题讨论】:
-
在文本编辑器中检查文件的内容,看看它是否真的如您所愿。
-
@PeeHaa 是的。当我从服务器正常下载文件时,它可以工作。
-
@Martin 没有帮助。我仍然遇到同样的错误。
-
好的,那么我会冒险您的文件大小不完全正确,因此请尝试注释掉 Content-Length 标头并查看下载是否使用动态大小而不是规定的固定大小.
-
@RyanVincent 我查过了。但是,我不明白两个文件中发生了什么。但是,这是结果:已添加(155)已删除(796)已更改(405)
标签: php