2016-12-28 161 views
1

我想我所有的图像导出在一个zip,但由于某种原因它增加了我的所有本地磁盘的太...我不明白..PHP创建zip压缩包添加了本地磁盘

这是代码:

$files = $urls; 
$zipname = 'uploads.zip'; 
$zip = new ZipArchive; 
$zip->open($zipname, ZipArchive::CREATE); 

foreach ($files as $file) { 
    $name = explode('/', $file); 
    $zip->addFile($file, pathinfo($file, PATHINFO_BASENAME)); 
} 

$zip->close(); 

header('Content-Type: application/zip'); 
header('Content-disposition: attachment; filename='.$zipname); 
header('Content-Length: ' . filesize($zipname)); 

readfile($zipname); 

$files是图像的位置的数组:

ServicesController.php on line 61: 
array:3 [▼ 
    0 => "C:\wamp\www\prjct\app/../../prjct/web/uploads/media/default/0001/15/thumb_14794_default_big.gif" 
    1 => "C:\wamp\www\prjct\app/../../prjct/web/uploads/media/default/0001/15/thumb_14794_default_small.gif" 
    2 => "C:\wamp\www\prjct\app/../../prjct/web/uploads/media/default/0001/15/thumb_14794_admin.gif" 
] 

当我opne我的zip文件,我看到这一点:

enter image description here

正如你可以看到有我的本地磁盘魔女不应该在这里..

+1

什么是$网址变量?你可以打印它吗? – nagiyevel

+0

你能上传创建的zip文件吗?它的尺寸是多少? – yivi

回答

0

这应该工作:

$files = $urls; 
$zipname = 'uploads.zip'; 
$zip = new ZipArchive; 
$zip->open($zipname, ZipArchive::CREATE); 

$rootPath = realpath($files); 
$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootPath), 
    RecursiveIteratorIterator::LEAVES_ONLY 
); 

foreach ($files as $name => $file) { 
    // Get real and relative path for current file 
    $filePath = $file->getRealPath(); 
    $relativePath = substr($filePath, strlen($rootPath) + 1); 

    // non-empty directories would be added automatically 
    if (!$file->isDir()){ 
     // Add current file to archive 
     $zip->addFile($filePath, $relativePath);  
    } 
} 

$zip->close(); 

一般情况下,你应该使用DIRECTORY_SEPARATOR预定义的常量,而不是斜杠/反斜杠。这在Windows机器上开发时特别有用。

通常,在Windows上工作时,确保在向zip文件添加文件夹时删除尾部斜杠 - 这就是在zip文件中创建本地磁盘的原因。

$localDirNoSlashes = rtrim($localDir, DIRECTORY_SEPARATOR); 
$zip->addEmptyDir($localDirNoSlashes); 

这是推动我疯了一段时间,直到我意识到是怎么回事...