php glob-在子文件夹中扫描文件 [英] php glob - scan in subfolders for a file

查看:113
本文介绍了php glob-在子文件夹中扫描文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一台服务器,该服务器的各个文件夹,子文件夹和子子文件夹中都有很多文件.

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.

这是我到目前为止所拥有的:

Here's what i have so far:

$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.

推荐答案

有2种方法.

使用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;
}

?>

使用RecursiveDirectoryIterator

<?php
function rsearch($folder, $pattern) {
    $dir = new RecursiveDirectoryIterator($folder);
    $ite = new RecursiveIteratorIterator($dir);
    $files = new RegexIterator($ite, $pattern, RegexIterator::GET_MATCH);
    $fileList = array();
    foreach($files as $file) {
        $fileList = array_merge($fileList, $file);
    }
    return $fileList;
}
?>

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆