我试图强制下载受保护的 zip 文件(我不希望人们在没有先登录的情况下访问它。
我为以下创建了函数login
等等,但我遇到了下载的文件损坏的问题。
这是我的代码:
$file='../downloads/'.$filename;
header("Content-type: application/zip;\n");
header("Content-Transfer-Encoding: Binary");
header("Content-length: ".filesize($file).";\n");
header("Content-disposition: attachment; filename=\"".basename($file)."\"");
readfile("$file");
exit();
这是错误:Cannot open file: It does not appear to be a valid archive.
否则文件下载得很好,所以这一定是我对标头做错了。
有任何想法吗?
此问题可能有多种原因。也许你的文件没有找到或者无法读取,因此文件的内容只是 PHP 错误消息。或者 HTTP 标头已经发送。或者您有一些额外的输出,然后会损坏文件的内容。
尝试在脚本中添加一些错误处理,如下所示:
$file='../downloads/'.$filename;
if (headers_sent()) {
echo 'HTTP header already sent';
} else {
if (!is_file($file)) {
header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found');
echo 'File not found';
} else if (!is_readable($file)) {
header($_SERVER['SERVER_PROTOCOL'].' 403 Forbidden');
echo 'File not readable';
} else {
header($_SERVER['SERVER_PROTOCOL'].' 200 OK');
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: Binary");
header("Content-Length: ".filesize($file));
header("Content-Disposition: attachment; filename=\"".basename($file)."\"");
readfile($file);
exit;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)