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

时间:2018-12-18 16:34:10

标签: php 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:\Users\MINORA~1.ONE\AppData\Local\Temp\download,C:\Users\MINORA~1.ONE\AppData\Local\Temp\download): Impossibile trovare il percorso specificato.
Warning: Unknown: Cannot destroy the zip context in Unknown on line 0

1 个答案:

答案 0 :(得分:0)

不知道上面的代码是否正确/正确,但结果发现错误中缺少$format$command周围的双引号,从而导致没有输出,因此{{1 }}未创建。

我忘了放它们了,因为我认为一个字符串变量会包含这些变量,但是当然,这只是构造一个字符串变量的方式。我要么必须做$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\"