php header 文件传输损坏

php header file transfer corrupted

我的文件夹中有一些文件。我使用以下 php 代码将文件传输到浏览器(使用 headers)。

我下载了正确长度的 .7z 格式文件,但无法解压缩。 如果我用 ftp 传输相同的文件,我可以毫无问题地解压缩它。 从我的服务器我可以毫无问题地将它解压缩到。所以错误在 php

的某处
    private function pushToBrowser($file){
    if(!$file){ // file does not exist
        die('file not found');
    } else {
        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header("Content-Disposition: attachment; filename=$file");
        header("Content-Type: application/zip");
        header("Content-Transfer-Encoding: binary");
        header("Content-length: ".filesize($file).";\n");

        // read the file from disk
        readfile($file);
    }
}

代码的用法

$this->pushToBrowser($path);

For serving 7 zip files your content type should be application/x-7z-compressed

如果您同时提供 7 zip 和 zip 或 rar 文件,则必须以编程方式将内容类型设置为浏览器。

在你调用 readfile($path) 之前做一个 ob_clean(); & flush();

所以最后你的代码应该是这样的:

private function pushToBrowser($file){
    if(!$file){ // file does not exist
        die('file not found');
    } else {
        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header("Content-Disposition: attachment; filename=$file");
        header("Content-Type: application/x-7z-compressed");
        header("Content-Transfer-Encoding: binary");
        header("Content-length: ".filesize($file).";\n");
        ob_clean();
        flush();
        // read the file from disk
        readfile($file);
    }
}