php glob - 在子文件夹中扫描文件 [英] php glob - scan in subfolders for a file
问题描述
我有一台服务器,在各种文件夹、子文件夹和子子文件夹中都有很多文件.
I have a server with a lot of files inside various folders, sub-folders, and sub-sub-folders.
我正在尝试制作一个 search.php 页面,用于在整个服务器中搜索特定文件.如果找到文件,则返回位置路径以显示下载链接.
I'm trying to make a search.php page that would be used to search the whole server for a specific file. If the file is found, then return the location path to display a download link.
这是我目前所拥有的:
$root = $_SERVER['DOCUMENT_ROOT'];
$search = "test.zip";
$found_files = glob("$root/*/test.zip");
$downloadlink = str_replace("$root/", "", $found_files[0]);
if (!empty($downloadlink)) {
echo "<a href="http://www.example.com/$downloadlink">$search</a>";
}
如果文件在我的域名根目录内,脚本运行良好...现在我正在尝试找到一种方法让它也扫描子文件夹和子子文件夹,但我被卡住了在这里.
The script is working perfectly if the file is inside the root of my domain name... Now i'm trying to find a way to make it also scan sub-folders and sub-sub-folders but i'm stuck here.
推荐答案
有两种方法.
使用glob
进行递归搜索:
<?php
// Does not support flag GLOB_BRACE
function rglob($pattern, $flags = 0) {
$files = glob($pattern, $flags);
foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) {
$files = array_merge($files, rglob($dir.'/'.basename($pattern), $flags));
}
return $files;
}
// usage: to find the test.zip file recursively
$result = rglob($_SERVER['DOCUMENT_ROOT'] . '/test.zip');
var_dump($result);
// to find the all files that names ends with test.zip
$result = rglob($_SERVER['DOCUMENT_ROOT'] . '/*test.zip');
?>
使用RecursiveDirectoryIterator
<?php
// $regPattern should be using regular expression
function rsearch($folder, $regPattern) {
$dir = new RecursiveDirectoryIterator($folder);
$ite = new RecursiveIteratorIterator($dir);
$files = new RegexIterator($ite, $regPattern, RegexIterator::GET_MATCH);
$fileList = array();
foreach($files as $file) {
$fileList = array_merge($fileList, $file);
}
return $fileList;
}
// usage: to find the test.zip file recursively
$result = rsearch($_SERVER['DOCUMENT_ROOT'], '/.*/test.zip/'));
var_dump($result);
?>
RecursiveDirectoryIterator
来自 PHP5 而 glob
来自 PHP4.两者都可以胜任,这取决于您.
RecursiveDirectoryIterator
comes with PHP5 while glob
is from PHP4. Both can do the job, it's up to you.
这篇关于php glob - 在子文件夹中扫描文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!