繁体   English   中英

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

[英]PHP creating zip archive adds local disk

我想以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文件时,我看到了这个:

在此输入图像描述

你可以看到我的本地磁盘女巫不应该在这里..

这应该工作:

$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);

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM