PHP提供了ZipArchive类,可以实现指定文件打包,并下载的功能。 可是,当文件比较多比较大的时候,打包需要很长时间处理,这样就需要用户等待,体验不是很好。 这时候,我们可以使用管道机制,不生成压缩包,而是一边压缩一边下载。这个功能需要用到popen函数和zip命令。

代码实现

使用 popen函数和zip命令,实现Zip内存打包下载。

<?php
function action_index()
{
    $files = glob("D:\BaiduNetdiskDownload\ApwWnmp2021.6-原始软件列表\php\*");
    header('Pragma: no-cache');
    header('Content-Description: File Download');
    header('Content-disposition: attachment; filename="myZip.zip"');
    header('Content-Type: application/octet-stream');
    header('Content-Transfer-Encoding: binary');

    //Opening a zip stream
    $files = implode(" ", $files);
    if ($files){
        $fp = popen('zip -q -r -0 -j - ' . $files, 'r');
    }

    $index = 0;
    while(!feof($fp)) {
        echo fread($fp, 8192);
        $index++;
        if ($index % 1024 == 0){
            ob_flush();
            flush();
        }
    }

    //Closing the stream
    if ($files){
        pclose($fp);
    }
}

微信点赞