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

我正试图强制下载受保护的zip文件(我不希望人们在没有先登录的情况下访问它.

我有登录创建的功能等,但我遇到了下载文件损坏的问题.

这是我的代码

$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();

这是错误:无法打开文件:它似乎不是有效的存档.

否则文件下载正常,所以它必须是我在标题上做错的事情.

有任何想法吗?

解决方法:

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

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...