2010-10-22 227 views
43

我想用php创建一个zip文件(它从 - 这个页面 - http://davidwalsh.name/create-zip-php),但是在zip文件里面是所有的文件夹名称文件本身。php创建zip文件夹内没有文件路径

是否有可能将zip文件中的文件减去所有文件夹?

这里是我的代码:

function create_zip($files = array(), $destination = '', $overwrite = true) { 

    if(file_exists($destination) && !$overwrite) { return false; }; 
    $valid_files = array(); 
    if(is_array($files)) { 
     foreach($files as $file) { 
      if(file_exists($file)) { 
       $valid_files[] = $file; 
      }; 
     }; 
    }; 
    if(count($valid_files)) { 
     $zip = new ZipArchive(); 
     if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) { 
      return false; 
     }; 
     foreach($valid_files as $file) { 
      $zip->addFile($file,$file); 
     }; 
     $zip->close(); 
     return file_exists($destination); 
    } else { 
     return false; 
    }; 

}; 


$files_to_zip = array('/media/138/file_01.jpg','/media/138/file_01.jpg','/media/138/file_01.jpg'); 

$result = create_zip($files_to_zip,'/...full_site_path.../downloads/138/138_files.zip'); 
+1

尝试'-D'开关(大写!) – drudge 2010-10-22 01:01:00

回答

107

这里的问题是,$zip->addFile被传递相同的两个参数。

根据the documentation

布尔ZipArchive :: addFile(字符串$文件名 [,串$的localName])


到该文件的路径加上。

localname
ZIP归档中的本地名称。

这意味着,第一个参数是路径到文件系统中的实际文件,第二个是路径&文件名,文件将在归档。

当您提供第二个参数时,您需要在将其添加到zip归档文件时从其中删除路径。例如,在基于Unix的系统中,这看起来像:

$new_filename = substr($file,strrpos($file,'/') + 1); 
$zip->addFile($file,$new_filename); 
+0

非常感谢:) – SoulieBaby 2010-10-22 03:13:30

+0

奇怪的是,这个相同的问题也随之而来,在两次两天... http://stackoverflow.com/questions/3988496/how-to-add-a-txt-file-and-create-a-zip-in-php/3989210#3989210 – 2010-10-22 11:00:40

+0

LOL受欢迎的问题?奇怪。 – SoulieBaby 2010-10-24 21:29:01

33

我认为一个更好的选择是:

$zip->addFile($file,basename($file)); 

简单地提取从路径的文件名。

+1

完美的答案 - 像一个魅力! – Hexodus 2016-02-16 00:07:40

+0

不知道有一个内置的PHP [basename](http://php.net/manual/en/function.basename.php)函数 – 2016-07-28 18:57:38

0

这仅仅是另一种方法,我发现,工作对我来说

$zipname = 'file.zip'; 
$zip = new ZipArchive(); 
$tmp_file = tempnam('.',''); 
$zip->open($tmp_file, ZipArchive::CREATE); 
$download_file = file_get_contents($file); 
$zip->addFromString(basename($file),$download_file); 
$zip->close(); 
header('Content-disposition: attachment; filename='.$zipname); 
header('Content-type: application/zip'); 
readfile($tmp_file);