2016-12-28 162 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); 

這是推動我瘋了一段時間,直到我意識到是怎麼回事...