使用 exec 创建文件夹后对其进行 ZIP 压缩会导致不创建文件夹并且压缩失败



我有一个脚本应该(按顺序):

  1. sys_get_temp_dir()中创建一个文件夹,并在其中放置一些文件(在exec()行内完成)
  2. 压缩文件夹及其内容
  3. 强制下载客户端

我分别成功地尝试了步骤 1 和 3,但努力使步骤 2 起作用。

我的脚本是这个(在我得到的错误下面):

<?php
$tmpdir = sys_get_temp_dir();
$outdir = "download";
$format = "ESRI Shapefile";
$folderToZip = $tmpdir . DIRECTORY_SEPARATOR . $outdir;
$command = "ogr2ogr -f $format $folderToZip WFS:"https://www.wondermap.it/cgi-bin/qgis_mapserv.fcgi?&map=/home/ubuntu/qgis/projects/Demo_sci_WMS/demo_sci.qgs&SERVICE=WFS&VERSION=1.1.0&REQUEST=GetFeature&typename=domini_sciabili&bbox=544138,5098446,564138,5108446" --config GDAL_HTTP_UNSAFESSL YES";
exec($command);
// Initialize archive object
$zip = new ZipArchive();
$zipFile = "download.zip";
$zip->open($zipFile, ZipArchive::CREATE | ZipArchive::OVERWRITE);
// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($folderToZip),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file)
{
// Skip directories (they would be added automatically)
if (!$file->isDir())
{
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($folderToZip) + 1);
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
// Zip archive will be created only after closing object
$zip->close();
header("Content-Description: File Transfer");
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=" . $zipFile);
readfile ($zip);
exit();
?>

我得到的错误:

Fatal error: Uncaught exception 'UnexpectedValueException' with message 'RecursiveDirectoryIterator::__construct(C:UsersMINORA~1.ONEAppDataLocalTempdownload,C:UsersMINORA~1.ONEAppDataLocalTempdownload): Impossibile trovare il percorso specificato.
Warning: Unknown: Cannot destroy the zip context in Unknown on line 0

不知道上面的代码是否完全正确,但事实证明错误在$command$format周围缺少双引号,这反过来又没有产生输出,因此没有创建$folderToZip

我忘了放它们,因为我认为字符串变量会包含这些,但当然这只是字符串变量的构造方式。要么我必须做$format = "'ESRI Shapefile'";(而不是$format = "ESRI Shapefile";),要么(这就是我所做的),我需要在$command中明确地添加双引号,例如

$command = "ogr2ogr -f "$format" $folderToZip WFS:"https://www.wondermap.it/cgi-bin/qgis_mapserv.fcgi?&map=/home/ubuntu/qgis/projects/Demo_sci_WMS/demo_sci.qgs&SERVICE=WFS&VERSION=1.1.0&REQUEST=GetFeature&typename=domini_sciabili&bbox=544138,5098446,564138,5108446" --config GDAL_HTTP_UNSAFESSL YES";

,写"$format"而不是$format

最新更新