Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

like image 939
Winston Smith Avatar asked Jun 18 '13 04:06

Winston Smith


4 Answers

There are 2 ways.

Use glob to do recursive search:

<?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');
?>

Use 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 comes with PHP5 while glob is from PHP4. Both can do the job, it's up to you.

like image 58
Tony Chen Avatar answered Nov 16 '22 18:11

Tony Chen


I want to provide another simple alternative for cases where you can predict a max depth. You can use a pattern with braces listing all possible subfolder depths.

This example allows 0-3 arbitrary subfolders:

glob("$root/{,*/,*/*/,*/*/*/}test_*.zip", GLOB_BRACE);

Of course the braced pattern could be procedurally generated.

like image 34
Quasimodo's clone Avatar answered Nov 16 '22 17:11

Quasimodo's clone


This returns fullpath to the file

function rsearch($folder, $pattern) {
    $iti = new RecursiveDirectoryIterator($folder);
    foreach(new RecursiveIteratorIterator($iti) as $file){
         if(strpos($file , $pattern) !== false){
            return $file;
         }
    }
    return false;
}

call the function:

$filepath = rsearch('/home/directory/thisdir/', "/findthisfile.jpg");

And this is returns like:

/home/directory/thisdir/subdir/findthisfile.jpg

You can improve this function to find several files like all jpeg file:

function rsearch($folder, $pattern_array) {
    $return = array();
    $iti = new RecursiveDirectoryIterator($folder);
    foreach(new RecursiveIteratorIterator($iti) as $file){
        if (in_array(strtolower(array_pop(explode('.', $file))), $pattern_array)){
            $return[] = $file;
        }
    }
    return $return;
}

This can call as:

$filepaths = rsearch('/home/directory/thisdir/', array('jpeg', 'jpg') );

Ref: https://stackoverflow.com/a/1860417/219112

like image 9
Sadee Avatar answered Nov 16 '22 17:11

Sadee


As a full solution for your problem (this was also my problem):

<?php
function rsearch($folder, $pattern) {
    $dir = new RecursiveDirectoryIterator($folder);
    $ite = new RecursiveIteratorIterator($dir);
    $files = new RegexIterator($ite, $pattern, RegexIterator::MATCH);


    foreach($files as $file) {
         yield $file->getPathName();
    }
}

Will get you the full path of the items that you wish to find.

Edit: Thanks to Rousseau Alexandre for pointing out , $pattern must be regular expression.

like image 7
metzelder Avatar answered Nov 16 '22 19:11

metzelder