PHP创建zip存档添加本地磁盘

时间:2016-12-28 11:12:58

标签: php zip

我想以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"
]

当我查看我的zip文件时,我看到了:

enter image description here

正如你所看到的,我的本地磁盘女巫不应该在这里..

1 个答案:

答案 0 :(得分: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);

这让我疯狂了一段时间,直到我意识到发生了什么......

相关问题