2012-07-12 68 views
5

我用php压缩文件夹和文件,但是当我尝试打开压缩文件时,我得到一个cpgz文件。解压缩文件后,我得到另一个zip文件。它做什么是低音扫描当前文件夹的文件和文件夹压缩。 这是我使用的代码:我只是有完全相同的问题用PHP压缩文件解压后得到cpgz文件

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); 
} 
+0

- @ Steven,是你的应用程序代码在同一台服务器上的zip文件吗?我有这个完全相同的问题,我[这里解决](http://stackoverflow.com/questions/11495103/opening-downloaded-zip-file-creates-cpgz-file)。另外,你有什么'header()'的样子? – 2012-07-15 21:15:15

回答

6

,并了解到,这两个函数调用可以帮助:

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

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

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

通常设置内容处置和内容长度应该已经足够了,但是在PHP设置标题之前,刷新PHP输出缓冲区和底层输出缓冲区(Apache或类似的)有助于输出意外发送。

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

希望在未来帮助某人。