【问题标题】:Zipped file with PHP results in cpgz file after extraction使用 PHP 压缩的文件在提取后生成 cpgz 文件
【发布时间】:2012-07-12 14:33:20
【问题描述】:

我正在使用 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);
}

【问题讨论】:

  • -@Steven,您的 zip 文件与您的应用程序代码在同一台服务器上吗?我遇到了与resolved here 完全相同的问题。另外,你header()'s 长什么样子?

标签: php zip


【解决方案1】:

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

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() 调用有助于查看在发送文件之前输出警告。

希望对未来的人有所帮助。

【讨论】:

  • 谢谢,工作!我很好奇为什么需要这些。
猜你喜欢
  • 2014-10-23
  • 1970-01-01
  • 2011-05-02
  • 2016-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多