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

时间:2012-07-12 14:33:20

标签: php zip

我用php压缩文件夹和文件,但是当我尝试打开zip文件时,我得到了一个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);
}

1 个答案:

答案 0 :(得分:7)

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

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

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

readfile($filename);
unlink($filename);

通常设置Content-Disposition和Content-Length应该足够了,但是在PHP中设置标头之前意外发送输出时,刷新PHP输出缓冲区和底层输出缓冲区(Apache等)会有所帮助。

在我的情况下,注释掉header()和readfile()调用有助于查看在发送文件之前输出的警告。

希望将来帮助某人。

相关问题