我有一个ZIPS目录的脚本,但也需要添加* .php文件。
添加类似../ index.php。
之类的东西时会抛出问题以下脚本产生的错误是:
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
我的剧本:
<?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;
?>
我在http://php.net/manual/en/class.recursiveiteratoriterator.php阅读了有关RecursiveIteratorIterator的内容,此处还有许多问题没有解决问题。
仅用../替换../index.php,但包含不希望放在zip中的目录。
任何允许在下载的zip中插入php的输入都非常赞赏。
答案 0 :(得分:1)
您可以使用FilterIterator
或CallbackFilterIterator
。如果您在多个地方使用相同的过滤器,最好使用FilterIterator
。为简单起见,我使用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);
}
注意FilesystemIterator::SKIP_DOTS
旗帜。它可以帮助您避免这样的代码:
if ($file->getFilename() != '.' && $file->getFilename() != '..') {
// ...
}
另一种方法是使用原始代码仅添加目录,但对于文件使用ZipArchive::addPattern
方法:
$zip->addPattern('/\.(?:php)$/', $path)
请注意,模式将仅与文件名匹配。