简体   繁体   English

RecursiveIteratorIterator:在zip中包含目录和php文件

[英]RecursiveIteratorIterator: include directory and php files in zip

I have a script which ZIPS directories, but need to add *.php files also. 我有一个包含ZIPS目录的脚本,但是还需要添加* .php文件。

Issue having is error is thrown when adding something like ../index.php. 添加../index.php之类的东西时会引发错误问题。

Error produced by script below is: 以下脚本产生的错误是:

Fatal error: Uncaught exception 'UnexpectedValueException' with message 'RecursiveDirectoryIterator::__construct(../index.php): failed to open dir: Not a directory' in /home/mathtest/public_html/trig/admin/save.php:23 Stack trace: #0 /home/mathtest/public_html/trig/admin/save.php(23): RecursiveDirectoryIterator->__construct('../index.php') #1 {main} thrown in /home/mathtest/public_html/trig/admin/save.php on line 23

My script: 我的剧本:

<?php

/* CONFIG */

$pathToAssets = array("../images", "../Data", "../css", "../index.php");

$filename = "temp/backup.zip";

/* END CONFIG */


$zip = new ZipArchive();

$zip->open($filename, ZipArchive::CREATE);


//add folder structure

foreach ($pathToAssets as $thePath) {

    // Create recursive directory iterator
    $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($thePath), RecursiveIteratorIterator::LEAVES_ONLY
    );


    foreach ($files as $name => $file) {

        if ($file->getFilename() != '.' && $file->getFilename() != '..') {

            // Get real path for current file
            $filePath = $file->getRealPath();

            $temp = explode("/", $name);

            array_shift($temp);

            $newName = implode("/", $temp);

            // Add current file to archive
            $zip->addFile($filePath, $newName);
        }
    }
}

$zip->close();

$yourfile = $filename;

$file_name = basename($yourfile);

header("Content-Type: application/zip");
header("Content-Transfer-Encoding: Binary");
header("Content-Disposition: attachment; filename=$file_name");
header("Content-Length: " . filesize($yourfile));

readfile($yourfile);

unlink('temp/backup.zip');

exit;
?>

I have read about RecursiveIteratorIterator at http://php.net/manual/en/class.recursiveiteratoriterator.php and also many questions here without luck in solving. 我已经在http://php.net/manual/en/class.recursiveiteratoriterator.php上阅读了有关RecursiveIteratorIterator的信息,这里还有很多问题,没有运气可以解决。

Replacing ../index.php with just ../ works, but that includes directories that do not want placed in zip. 仅用../代替../index.php即可,但是其中包括不想放在zip中的目录。

Any input to allow insertion of php in downloaded zip much appreciated. 任何允许在下载的zip中插入php的输入都非常感谢。

You can use FilterIterator or CallbackFilterIterator . 您可以使用FilterIteratorCallbackFilterIterator If you use the same filters in multiple places better to use FilterIterator . 如果您在多个地方使用相同的过滤器,最好使用FilterIterator For the simplicity, I use CallbackFilterIterator and define the filter function that uses preg_match to decide whether the file will be present in the loop. 为简单起见,我使用CallbackFilterIterator并定义使用preg_match来决定文件是否存在于循环中的过滤器函数。

$path = '../test';

$directories = ['images', 'Data', 'css'];

$filter = function ($current, $key, $iterator) use ($path, $directories) {
    $path = preg_quote($path, '/');
    $directories = implode('|', array_map('preg_quote', $directories));

    if (preg_match('/^' . $path . '\/(' . $directories . ')/', $key)) {
        return true;
    }

    if (preg_match('/^' . $path . '.+\.php$/', $key)) {
        return true;
    }

    return false;
};

$files = new CallbackFilterIterator(
    new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator(
            $path,
            FilesystemIterator::SKIP_DOTS
        ),
        RecursiveIteratorIterator::LEAVES_ONLY
    ),
    $filter
);

foreach ($files as $key => $file) {
    // Do something with files.
    var_dump($key, $file);
}

Take a notice of FilesystemIterator::SKIP_DOTS flag. 注意FilesystemIterator::SKIP_DOTS标志。 It helps you to avoid code like this: 它可以帮助您避免这样的代码:

if ($file->getFilename() != '.' && $file->getFilename() != '..') {
    // ...
}

The other approach will be to use your original code to add directories only, but for files use ZipArchive::addPattern method: 另一种方法是使用原始代码仅添加目录,但对于文件,请使用ZipArchive::addPattern方法:

$zip->addPattern('/\.(?:php)$/', $path)

Be aware, that the pattern will be matched against the file name only . 请注意, 该模式将仅与文件名匹配

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

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