下载.zip文件运行损坏的文件php

2022-08-30 22:44:02

我正在尝试强制下载受保护的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.

否则文件下载正常,所以它一定是我在标题上做错了什么。

有什么想法吗?


答案 1

此问题可能有多种原因。可能您的文件未找到或无法读取,因此文件的内容只是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;
    }
}

答案 2

我打赌两个啤酒发生PHP错误,错误消息搞砸了ZIP文件。请求的文件可能不存在。

使用记事本或类似的文本编辑器打开ZIP文件,然后找出问题所在。


推荐