使用PHP压缩的文件在提取后将生成cpgz文件

使用PHP压缩的文件在提取后将生成cpgz文件,php,zip,Php,Zip,我正在用php压缩文件夹和文件,但是当我试图打开压缩文件时,我得到了一个cpgz文件。解压该文件后,我得到另一个zip文件。它所做的是基本扫描当前文件夹中要压缩的文件和文件夹。 这是我使用的代码: function Zip($source, $destination) { if (!extension_loaded('zip') || !file_exists($source)) { return false; } $zip = new ZipArchive(); if (!$zip-

我正在用php压缩文件夹和文件,但是当我试图打开压缩文件时,我得到了一个cpgz文件。解压该文件后,我得到另一个zip文件。它所做的是基本扫描当前文件夹中要压缩的文件和文件夹。 这是我使用的代码:

function Zip($source, $destination)
{
if (!extension_loaded('zip') || !file_exists($source)) {
    return false;
}

$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
    return false;
}

$source = str_replace('\\', '/', realpath($source));

if (is_dir($source) === true)
{
    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

    foreach ($files as $file)
    {
        $file = str_replace('\\', '/', realpath($file));

        if (is_dir($file) === true)
        {
            $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
        }
        else if (is_file($file) === true)
        {
            $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
        }
    }
}
else if (is_file($source) === true)
{
    $zip->addFromString(basename($source), file_get_contents($source));
}

return $zip->close();
}


if($_GET["archive"]== 'true'){
$date = date("Ymd_Hi");
$dir = dirname(__FILE__);
$filename = $date.".zip";

Zip(getcwd(), $filename);

header("Content-disposition: attachment; filename=$filename");
header('Content-type: application/zip');
readfile($filename);
unlink($filename);
}

我刚刚遇到了完全相同的问题,并且了解到这两个函数调用可以帮助:

header("Content-disposition: attachment; filename=$filename");
header('Content-type: application/zip');

// Add these
ob_clean();
flush();

readfile($filename);
unlink($filename);
通常,设置内容配置和内容长度应该足够了,但是在PHP中设置头之前意外发送输出时,刷新PHPs输出缓冲区和底层输出缓冲区(Apache或类似)会有所帮助

在我的例子中,注释掉header()和readfile()调用以进行调试有助于看到警告是在文件发送之前输出的


希望这对将来有帮助。

-@Steven,你的zip文件和你的应用程序代码在同一台服务器上吗?我遇到了和我一样的问题。另外,您的
header()是什么样子的?
谢谢,很好用!我很好奇为什么需要这些。