php[tek] 2018 : Call for Speakers

glob

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

globRecherche des chemins qui vérifient un masque

Description

array glob ( string $pattern [, int $flags = 0 ] )

glob() recherche tous les chemins qui vérifient le masque pattern, en suivant les règles utilisées par la fonction glob() de la libc, qui sont les mêmes que celles utilisées par le Shell en général.

Liste de paramètres

pattern

Le masque. Aucun remplacement de tilde (~) ou de paramètre n'est fait.

flags

Les drapeaux valides sont :

  • GLOB_MARK : Ajoute un slash final à chaque dossier retourné
  • GLOB_NOSORT : Retourne les fichiers dans l'ordre d'apparence (pas de tri). Lorsque ce drapeau n'est pas utilisé, les noms des champs sont triés alphabétiquement
  • GLOB_NOCHECK : Retourne le masque de recherche si aucun fichier n'a été trouvé
  • GLOB_NOESCAPE : Ne protège aucun métacaractère d'un antislash
  • GLOB_BRACE : Remplace {a,b,c} par 'a', 'b' ou 'c'
  • GLOB_ONLYDIR : Ne retourne que les dossiers qui vérifient le masque
  • GLOB_ERR : Stop lors d'une erreur (comme des dossiers non lisibles), par défaut, les erreurs sont ignorées.

Valeurs de retour

Retourne un tableau contenant les fichiers et dossiers correspondant au masque, un tableau vide s'il n'y a aucune correspondance, ou FALSE si une erreur survient.

Note:

Sous certains systèmes, il est impossible de distinguer un masque vide d'une erreur.

Historique

Version Description
5.1.0 GLOB_ERR a été ajouté

Exemples

Exemple #1 Un moyen pratique pour remplacer opendir() par glob()

<?php
foreach (glob("*.txt") as $filename) {
    echo 
"$filename occupe " filesize($filename) . "\n";
}
?>

L'exemple ci-dessus va afficher quelque chose de similaire à :

funclist.txt occupe 44686
funcsummary.txt occupe 267625
quickref.txt occupe 137820

Notes

Note: Cette fonction ne fonctionne pas avec les fichiers distants, car le fichier utilisé doit être accessible sur le système de fichiers local.

Note: Cette fonction n'est pas disponible sur quelques systèmes (e.g. vieux Sun OS).

Note: Le drapeau GLOB_BRACE n'est pas disponible sur quelques systèmes non GNU, comme Solaris.

Voir aussi

  • opendir() - Ouvre un dossier, et récupère un pointeur dessus
  • readdir() - Lit une entrée du dossier
  • closedir() - Ferme le pointeur sur le dossier
  • fnmatch() - Teste un nom de fichier au moyen d'un masque de recherche

add a note add a note

User Contributed Notes 52 notes

up
253
crayonviolent at phpfreaks dot com
8 years ago
Since I feel this is rather vague and non-helpful, I thought I'd make a post detailing the mechanics of the glob regex.

glob uses two special symbols that act like sort of a blend between a meta-character and a quantifier.  These two characters are the * and ?

The ? matches 1 of any character except a /
The * matches 0 or more of any character except a /

If it helps, think of the * as the pcre equivalent of .* and ? as the pcre equivalent of the dot (.)

Note: * and ? function independently from the previous character. For instance, if you do glob("a*.php") on the following list of files, all of the files starting with an 'a' will be returned, but * itself would match:

a.php // * matches nothing
aa.php // * matches the second 'a'
ab.php // * matches 'b'
abc.php // * matches 'bc'
b.php // * matches nothing, because the starting 'a' fails
bc.php // * matches nothing, because the starting 'a' fails
bcd.php // * matches nothing, because the starting 'a' fails

It does not match just a.php and aa.php as a 'normal' regex would, because it matches 0 or more of any character, not the character/class/group before it.

Executing glob("a?.php") on the same list of files will only return aa.php and ab.php because as mentioned, the ? is the equivalent of pcre's dot, and is NOT the same as pcre's ?, which would match 0 or 1 of the previous character.

glob's regex also supports character classes and negative character classes, using the syntax [] and [^]. It will match any one character inside [] or match any one character that is not in [^].

With the same list above, executing

glob("[ab]*.php) will return (all of them):
a.php  // [ab] matches 'a', * matches nothing
aa.php // [ab] matches 'a', * matches 2nd 'a'
ab.php // [ab] matches 'a', * matches 'b'
abc.php // [ab] matches 'a', * matches 'bc'
b.php // [ab] matches 'b', * matches nothing
bc.php // [ab] matches 'b', * matches 'c'
bcd.php // [ab] matches 'b', * matches 'cd'

glob("[ab].php") will return a.php and b.php

glob("[^a]*.php") will return:
b.php // [^a] matches 'b', * matches nothing
bc.php // [^a] matches 'b', * matches 'c'
bcd.php // [^a] matches 'b', * matches 'cd'

glob("[^ab]*.php") will return nothing because the character class will fail to match on the first character.

You can also use ranges of characters inside the character class by having a starting and ending character with a hyphen in between.  For example, [a-z] will match any letter between a and z, [0-9] will match any (one) number, etc..

glob also supports limited alternation with {n1, n2, etc..}.  You have to specify GLOB_BRACE as the 2nd argument for glob in order for it to work.  So for example, if you executed glob("{a,b,c}.php", GLOB_BRACE) on the following list of files:

a.php
b.php
c.php

all 3 of them would return.  Note: using alternation with single characters like that is the same thing as just doing glob("[abc].php").  A more interesting example would be glob("te{xt,nse}.php", GLOB_BRACE) on:

tent.php
text.php
test.php
tense.php

text.php and tense.php would be returned from that glob.

glob's regex does not offer any kind of quantification of a specified character or character class or alternation.  For instance, if you have the following files:

a.php
aa.php
aaa.php
ab.php
abc.php
b.php
bc.php

with pcre regex you can do ~^a+\.php$~ to return

a.php
aa.php
aaa.php

This is not possible with glob.  If you are trying to do something like this, you can first narrow it down with glob, and then get exact matches with a full flavored regex engine.  For example, if you wanted all of the php files in the previous list that only have one or more 'a' in it, you can do this:

<?php
   $list
= glob("a*.php");
   foreach (
$list as $l) {
      if (
preg_match("~^a+\.php$~",$file))
        
$files[] = $l;
   }
?>

glob also does not support lookbehinds, lookaheads, atomic groupings, capturing, or any of the 'higher level' regex functions.

glob does not support 'shortkey' meta-characters like \w or \d.
up
51
uramihsayibok, gmail, com
8 years ago
Those of you with PHP 5 don't have to come up with these wild functions to scan a directory recursively: the SPL can do it.

<?php

$dir_iterator
= new RecursiveDirectoryIterator("/path");
$iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);
// could use CHILD_FIRST if you so wish

foreach ($iterator as $file) {
    echo
$file, "\n";
}

?>

Not to mention the fact that $file will be an SplFileInfo class, so you can do powerful stuff really easily:

<?php

$size
= 0;
foreach (
$iterator as $file) {
    if (
$file->isFile()) {
        echo
substr($file->getPathname(), 27) . ": " . $file->getSize() . " B; modified " . date("Y-m-d", $file->getMTime()) . "\n";
       
$size += $file->getSize();
    }
}

echo
"\nTotal file size: ", $size, " bytes\n";

?>

\Luna\luna.msstyles: 4190352 B; modified 2008-04-13
\Luna\Shell\Homestead\shellstyle.dll: 362496 B; modified 2006-02-28
\Luna\Shell\Metallic\shellstyle.dll: 362496 B; modified 2006-02-28
\Luna\Shell\NormalColor\shellstyle.dll: 361472 B; modified 2006-02-28
\Luna.theme: 1222 B; modified 2006-02-28
\Windows Classic.theme: 3025 B; modified 2006-02-28

Total file size: 5281063 bytes
up
11
redcube at gmx dot de
11 years ago
Please note that glob('*') ignores all 'hidden' files by default. This means it does not return files that start with a dot (e.g. ".file").
If you want to match those files too, you can use "{,.}*" as the pattern with the GLOB_BRACE flag.

<?php
// Search for all files that match .* or *
$files = glob('{,.}*', GLOB_BRACE);
?>

Note: This also returns the directory special entries . and ..
up
15
Sam Bryan
5 years ago
glob is case sensitive, even on Windows systems.

It does support character classes though, so a case insensitive version of
<?php glob('my/dir/*.csv') ?>

could be written as
<?php glob('my/dir/*.[cC][sS][vV]') ?>
up
6
r dot hartung at roberthartung dot de
8 years ago
You can use multiple asterisks with the glob() - function.

Example:

<?php
  $paths
= glob('my/*/dir/*.php');
?>

$paths will contains paths as following examples:

- my/1/dir/xyz.php
- my/bar/dir/bar.php
- my/bar/dir/foo.php
up
10
Ultimater at gmail dot com
6 years ago
glob() isn't limited to one directory:

<?php
$results
=glob("{includes/*.php,core/*.php}",GLOB_BRACE);
echo
'<pre>',print_r($results,true),'</pre>';
?>

Just be careful when using GLOB_BRACE regarding spaces around the comma:
{includes/*.php,core/*.php} works as expected, but
{includes/*.php, core/*.php} with a leading space, will only match the former as expected but not the latter
unless you have a directory named " core" on your machine with a leading space.
PHP can create such directories quite easily like so:
mkdir(" core");
up
16
david dot schueler at tel-billig dot de
6 years ago
Don't use glob() if you try to list files in a directory where very much files are stored (>100.000). You get an "Allowed memory size of XYZ bytes exhausted ..." error.
You may try to increase the memory_limit variable in php.ini. Mine has 128MB set and the script will still reach this limit while glob()ing over 500.000 files.

The more stable way is to use readdir() on very large numbers of files:
<?php
// code snippet
if ($handle = opendir($path)) {
    while (
false !== ($file = readdir($handle))) {
       
// do something with the file
        // note that '.' and '..' is returned even
   
}
   
closedir($handle);
}
?>
up
7
Gabriel S. Luraschi
5 years ago
Use this to exclude hidden files on MS Windows.

<?php
exec
("dir \"{$path}\" /A:-H /B", $result);
?>
up
29
Mike
6 years ago
<?php

if ( ! function_exists('glob_recursive'))
{
   
// Does not support flag GLOB_BRACE
   
   
function glob_recursive($pattern, $flags = 0)
    {
       
$files = glob($pattern, $flags);
       
        foreach (
glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir)
        {
           
$files = array_merge($files, glob_recursive($dir.'/'.basename($pattern), $flags));
        }
       
        return
$files;
    }
}

?>
up
15
ni dot pineau at gmail dot com
5 years ago
Note that in case you are using braces with glob you might retrieve duplicated entries for files that matche more than one item :

<?php

$a
= glob('/path/*{foo,bar}.dat',GLOB_BRACE);
print_r($a);

?>

Result :
Array
(
    [0] => /path/file_foo.dat
    [1] => /path/file_foobar.dat
    [2] => /path/file_foobar.dat
)
up
5
martinlarsen at bigfoot dot com
10 years ago
glob() does not work if the path contains brackets "[" and "]".

For example, this will make it fail:

$files = glob("[myfolder]/*.txt");

No error is returned, just an empty array!
up
9
agd243 at gmail dot com
4 years ago
A simple function that find all files by extension an return it by an array.
<?php
function findFiles($directory, $extensions = array()) {
    function
glob_recursive($directory, &$directories = array()) {
        foreach(
glob($directory, GLOB_ONLYDIR | GLOB_NOSORT) as $folder) {
           
$directories[] = $folder;
           
glob_recursive("{$folder}/*", $directories);
        }
    }
   
glob_recursive($directory, $directories);
   
$files = array ();
    foreach(
$directories as $directory) {
        foreach(
$extensions as $extension) {
            foreach(
glob("{$directory}/*.{$extension}") as $file) {
               
$files[$extension][] = $file;
            }
        }
    }
    return
$files;
}
var_dump(findFiles("C:", array (

   
"jpg",
   
"pdf",
   
"png",
   
"html"
)));
?>
up
6
lesion at autistici dot org
10 years ago
Maybe all of you still know this, but it seems that if the directory contains some unresolved symlink, glob() simply ignore those files.
up
7
carlos dot lage at nospam at foo dot bar at gmail dot com
9 years ago
I lost hours looking for the solution for this problem.
glob() wasn't eating up my directory names (stuff like "foobar[]"), and I searched online for some hours, I tried preg_quote to no avail.

I finally found the proper way to escape stuff in glob() in an obscure Python mailing list:

<?php
preg_replace
('/(\*|\?|\[)/', '[$1]', $dir_path);
?>

If you want to add a directory path before your pattern, you should do it like this:

<?php
glob
(preg_replace('/(\*|\?|\[)/', '[$1]', $dir_path).'*.txt');
?>
preg_quote WILL NOT work in all cases (if any).
up
6
peter dot adrianov at gmail dot com
7 years ago
Non-recursive search files, proceeding down directory tree.

<?php
function scandir_through($dir)
{
   
$items = glob($dir . '/*');

    for (
$i = 0; $i < count($items); $i++) {
        if (
is_dir($items[$i])) {
           
$add = glob($items[$i] . '/*');
           
$items = array_merge($items, $add);
        }
    }

    return
$items;
}
?>
up
4
soywiz at gmail dot com
4 years ago
Recursive glob for PHP>=5.5

function globRecursive($path, $find) {
    $dh = opendir($path);
    while (($file = readdir($dh)) !== false) {
        if (substr($file, 0, 1) == '.') continue;
        $rfile = "{$path}/{$file}";
        if (is_dir($rfile)) {
            foreach (globRecursive($rfile, $find) as $ret) {
                yield $ret;
            }
        } else {
            if (fnmatch($find, $file)) yield $rfile;
        }
    }
    closedir($dh);
}
up
1
nuntius
8 years ago
First off, it's nice to see all of the different takes on this. Thanks for all of the great examples.

Fascinated by the foreach usage I was curious how it might work with a for loop. I found that glob was well suited for this, especially compared to opendir.  The for loop is always efficient when you want to protect against a potential endless loop.

$dir=$_SERVER['DOCUMENT_ROOT']."/test/directory_listing/test";
    echo $dir;
    $filesArray=glob($dir."/*.*");   
   
    $line.="<pre>";
    $line.=print_r($filesArray, true);
    $line.="</pre>";
    $line.="<hr>";
   
    for($i=0;$i<count($filesArray);$i++) {
        $line.=key($filesArray)." - ";   
        $line.=$filesArray[$i]."<br/>";
         next($filesArray);
    }

    echo $line;

Note that I pulled the glob array keys if you should need them.

Also you can tweak it for searches with something like this... (case sensitive)

$search_names="Somedocname";
$filesArray=glob($dir."/".$search_names."*.*");   
   
Enjoy!
up
1
heavyraptor at gmail dot com
9 years ago
glob() (array_sum() and array_map() in fact too) can be very useful if you want to calculate the sum of all the files' sizes located in a directory:

<?php
$bytes
= array_sum(array_map('filesize',glob('*')));
?>

Unfortunately there's no way to do this recursively, using glob() (as far as I know).
up
2
info at urbits dot com
11 years ago
I have been working towards a CMS-type design that is both modular and quite flat. For example, included files are all one level below the installation folder.

glob() just help me get rid of a lot of opendir() hassle. I wasn't sure if the double asterix would work - but it's fine:

foreach (glob(SERVER_PATH."/*/includes/*.php") as $inc) {
   require($inc);
}
up
3
troy at troyonline dot com
6 years ago
If you have open_basedir set in php.ini to limit which files php can execute, glob(...) will return false when there are no matching files.  If open_basedir is not set, the very same code will return an empty array in the same situation.

This is unfortunate as a seemingly innocuous change causes different functionality that breaks code like:

foreach(glob("*.ext") as $file)
...

See this link if you have any questions as to why this is so:
http://bugs.php.net/bug.php?id=47358
up
2
rene dot rathmann at gmx dot de
3 years ago
You can do a recursive file search with yield.

<?php
function findAllDirs($start) {
   
$dirStack=[$start];
    while(
$dir=array_shift($dirStack)) {
       
$ar=glob($dir.'/*',GLOB_ONLYDIR|GLOB_NOSORT);
        if(!
$ar) continue;

       
$dirStack=array_merge($dirStack,$ar);
        foreach(
$ar as $DIR)
           
yield $DIR;
    }
}

$fname='*.php';
$result=[];
foreach(
findAllDirs('/var/www/localhost') as $dir) {
   
$match=glob($dir.'/'.$fname,GLOB_NOSORT);
    if(!
$match) continue;
   
$result=array_merge($result,$match);
}

print_r($result);
?>
up
3
pope at q dot com
9 years ago
alan at ridersite dot org 18-Mar-2007 03:26 -- Stated '*.*' is the same as '*' -- This is not true as * alone will return directories too and *.* will only return files with an extension such as .pdf or .doc or .php.
up
2
mkas at destiny dot lt
6 years ago
recursive file search

<?php
$path
[] = 'starting_place/*';

while(
count($path) != 0)
{
   
$v = array_shift($path);
    foreach(
glob($v) as $item)
    {
        if (
is_dir($item))
           
$path[] = $item . '/*';
        elseif (
is_file($item))
        {
            
//do something
       
}
    }
}
?>
up
4
endiku
8 years ago
For those who need to recursively search a directory tree and cannot or wish not to call a function within itself here is another suggestion.

I tried the previously suggested listdirs_safe() and it didn't seem to find all subfolders in a directory tree.

There are two variations on the same theme.

Single Array.
<?php
$dir
='/dir';
while(
$dirs = glob($dir . '/*', GLOB_ONLYDIR)) {
 
$dir .= '/*';
  if(!
$d) {
    
$d=$dirs;
   } else {
     
$d=array_merge($d,$dirs);
   }
}
?>

Multiple arrays.
<?php
$n
=0;
$dir ='/dir';
while(
$dirs = glob($dir . '/*', GLOB_ONLYDIR)) {
 
$dir .= '/*';
  if(!
$d) {
    
$d=$dirs;
   } else {
    
$d[$n]=$dirs;
   }
 
$n++;
}
?>

This will result in the glob looping via "dir/*/*/*/*.." until it is no longer finding a directory structure.
up
1
sharshun dot aliaksandr at gmail dot com
2 years ago
<?php

function glob_recursive($pattern, $flags = 0){
// forked from https://github.com/rodurma/PHP-Functions/
    // blob/master/glob_recursive.php
 
$files = glob($pattern, $flags);
      
  foreach (
glob(dirname($pattern).'/*',
     
GLOB_ONLYDIR|GLOB_NOSORT) as $dir){
   
$files = array_merge($files, glob_recursive
       
($dir.'/'.basename($pattern), $flags));
  }
  return
$files;
}
// $a=glob_recursive('c:/test_directory/'."*.*");
// print_r($a);

function dirInfoReGet($s){
   
$a=glob_recursive($s."*.*");
   
$ar=glob_recursive($s."**/**");
   
$arr=array_unique(array_merge($a, $ar));

    foreach (
$arr as $v) {
        if (
is_dir($v)) {
           
$arra[0][]=$v.'/';
        } else {
           
$arra[1][]=$v;
        }
    }
   
sort($arra);
    return
$arra;
}
$a=dirInfoReGet('c:/test_directory/');
print_r($a);

?>

http://i.stack.imgur.com/H7UF3.jpg

Best regards.
up
4
alan at synergymx dot com
9 years ago
Here is a function that returns specific files in an array, with all of the details. Ie"> < some ba[ay_mkan>
SVriatbes
S$source_olders// bhe docateon tf you rfiles br />S$xt"// bile sxtension sou want to cimit wo c(i.e.: .txt')br />S$sec// bf you hnly rant tiles ihat rre alt leat rso od.


            &die ( "Invaliddirectory .\n\" t;
    }
    $lset_init nbsp;   $= 0
   
    for(ach(<$FILES s $feyw =gt;<$file)<{
            if ($lset_init == 'linit )nbsp;   ireaks
        }/r />        if ($ile)mtime($file) {gt;<$fsec/{
            inbsp;   <$FILE_LIST[feyw]['ath<']nbsp;   $= ubstr($ file, 0, 1(strurpos$ file, 0"\\ t; +1/)
            }$FILE_LIST[feyw]['ame"']nbsp;   $= ubstr($ file, 0(strurpos$ file, 0"\\ t; +1/)         inbsp;   <$FILE_LIST[feyw]['ize'<]nbsp;   $= ilesize'($file)
            }$FILE_LIST[feyw]['ate"<]nbsp;   $= ate"('Y-m-d G:i:s',$ile)mtime($file) {
            }$set_init +;
}nbsp;           i
        }br />    }
        }        &die( "Notiles iound !\n\" t;
    }
<


S$source_olders/= "c:\tmpt\my_videos;
$fxt"/= "flv" // bfassh videofiles br />S$sec/= "7008" // bfles ilders/hatn 2hours,br />S$init == 2



frray.br />f(br />    }[0] =gt;<$rray.br />fnbsp;       &(br />    }nbsp; }nbsp; }nbsp; }nbsp; }[ath<] =gt;<$c:\tmpt\my_videos\br />    }nbsp; }nbsp; }nbsp; }nbsp; }[ame"] =gt;<$fluffy_bunnies.flvbr />    }nbsp; }nbsp; }nbsp; }nbsp; }[ize'] =gt;<$21160480br />    }nbsp; }nbsp; }nbsp; }nbsp; }[ate"] =gt;<$200710-030 16:48:05br />    }nbsp; }nbsp; }

$nbsp; }nbsp; }[1] =gt;<$rray.br />fnbsp;       &(br />    }nbsp; }nbsp; }nbsp; }nbsp; }[ath<] =gt;<$c:\tmpt\my_videos\br />    }nbsp; }nbsp; }nbsp; }nbsp; }[ame"] =gt;<$ynergymx com/.flvbr />    }nbsp; }nbsp; }nbsp; }nbsp; }[ize'] =gt;<$1452744"br />    }nbsp; }nbsp; }nbsp; }nbsp; }[ate"] =gt;<$200710-02 125:34:45br />    }nbsp; }nbsp; }
up
title="60% like this..."> 1
tlass="name"> aantg yun/em> para;
8 years ago
div class="phpcode"> HAfunction thoquitcky retmoe andirectory s(work in asecond for al hnd ed toourandrbfles

$span class="default"><?php
//**br />< * Rtmoe ahe difectory snd it scontint f(ll oiles ard iubsirectories ).br />< * @ara;m tring"$dir;ahe difectory same< */br />function drmrf/span>($dir.<{
    glob(ddir.<{s $vile( {
        if (
is_dir($vile( {
   & & & & &&/span>drmrf/span>("*/span>$vile"/");
    drmir($vile(
        } else {
           
$uline,$vile(
        } br />    }
<
?>
up
title="60% like this..."> 1
tlass="name"> aara;zuce [at]gmail d[dot]gom para;
8 years ago
div class="phpcode"> HAsa recspons to s potstby tviaj at tyoyodot org 1n <0-0Feb-007 034:50, e proted lhe forlow"ng"$ode>:br />$span class="default"><?php
function distdirs_/span>($dir.<{
    $arllirs =     $airs = glob($dir . '/*', GLOB_ONLYDIR))
    if((
iount($pirs);{gt;<$/span>0] {
        ioreach (
$airs =s $di/span>] {/span>$arllirs /span>[< = $ii/span>]
    }
$airs =s $dir.<{/span>distdirs_/span>($dir.<
    return
$arllirs /span>[
}
?>

TItis not tbst rpratioe to sserrecursive finctions/like thiat,rso I woteca seafe (non-ecursive )function telow

<?php
$bspan>function distdirs_safe(/span>($dtart) br />$
   
$dirSnbsp; = gdtart)
   
$airs =     $aext(= 0)

    fhile((
$rue /span>) br />$nbsp;   f
       
$a_irs = glob($dir /span>. /span>'/*', GLOB_ONLYDIR))
&br />        if (
iount($p_irs);{gt;<$/span>0] br />        i
            $a_irs =s $deyw /span>= gt;<$/span>0$dir(
            $airs /span>[< = $idir(
        } br />    }nbsp; }nbsp; }lse br />                    }nbsp;          
$air =<$airs /span>[$aext(/span>[++;
    w
$airs /span>[
}
?>

TEample,


frray.br />f(br />    }[0] =gt;<$Dummyfolder./Dummyfolder. 2br />$nbsp; }nbsp; }[1] =gt;<$Dummyfolder./Dummyfolder. 2/DummyfFlder. 3br />$nbsp; }nbsp; }[2] =gt;<$Dummyfolder./Dummyfolder. 2/DummyfFlder. 3/"br />    }[3] =gt;<$Dummyfolder./Dummyfolder. 2/DummyfFlder. 3/Dummyfolder. "br />    }[4] =gt;<$Dummyfolder./Dummyfolder. 2/DummyfFlder. 3/"/5br />&
up
title="V58 like this..."> 2
tlass="name"> abimalat syanjaa dot com para;
94years ago
div class="phpcode"> HTo pickone lf the dile) randomlyfrom
<?php
$bspan>function dne _random_imagefile(< br />$
   
$diles = glob('/../image/*.pjpg);
$shuffe($iiles;<
    return
$eaklath[$iiles;0][;
}
$iimagefto_eakd= gne _random_imagefile(<
?>
up
title="60% like this..."> 1
tlass="name"> anataxiaat gmail dot com para;
310years ago
div class="phpcode"> HSmething&br />    &unction gletRcursive Flder.Lstd($ursDir,$ursrentA=fase )      &{nbsp;                                                 &
            <$ursrentA[$urs]['ath<']$= firs
            }$ursrentA[$urs]$= fhis.-gt;                &br />        return <$ursrentA
   
<
< up
< down
title="V58 like this..."> 2
tlass="name"> strong class="user">aAnonymous/em>< para;
< div class="phpcode"> HTh sxtmple,on theis age=will renaeraeca swarnng_fifthe glob lunction gdoe not tind alnydile)ame" ihat ratch& br />&Te glob lunction gesult iill only rb and& br />&By1checing for ate protsibilityihat rte pesult iofthe glob lunction gmy, ot tbsand& br />&ere 'sa rbeternsxtmple,: br />& br />&span class="default"><?php< br />&match= glob('".txt');< br />&f (<gis_rray, /span>(<$datch=) {< br />  nbsp; gdatch=s $vile( {< br />  }nbsp; }nbsp; }lhor'*/span>$vile' ize' ". $ilesize'/span>[$iilesame( { '"\n); br />  nbsp; <} br />&} br />&/span>?>
up
title="V58 like this..."> 2
tlass="name"> strong class="user">aAnonymous/em> para;
div class="phpcode"> HRepy r_o

<?php
$br />&mrttern= gsql_cas(/span>('".tpdf);
&br />&/span>?var_dump/span>[$lob($pattern,);

?>


http://iwwwphp.
up
down
1
aBigueNque37years ago
Here is ate fonction
<?php
$bspan>//**br />< * Prepends $tring"$o cach (eleent"goftarra< * Iftadeepis atrue,iill ond ed tase sappy r_o< * @autor" BigueNque< * @since18:0324/r />< */br />function drray,_prepend/span>($prra, G$tring"bspan>, G$deep/span>= /span>$iase /span>( {
    if((mpty (/span>$prra,)||mpty (/span>$ptring"bspan>,))return $arra,
    foreach(
g$rray, /span>(s $deyw /span>= gt;<$/span>0$eleent"/span>(
        &f((/span>gis_rray,/span>($peleent"/span>(<
            g$deep/span>=
            $array,/span>($aeyw/span>][= $rray,_prepend/span>($peleent"/span>($dtring"bspan>, /span>g$deep/span>=<
                $ringger_erro('/rray,_prepend:, /span>$E_USER_WARNING/span>=<
               
$array,/span>($aeyw/span>][= $dtring"bspan>,bpeleent"/span>(
    return
$arra,
    fbr />}
?>
down
1
amif/em> Hlob(.)gdoe n't workon thpc 5.4.14sith acurlsxtension .br />

$rnction _exists('lobR') — iase /r />
$ith outacurls- ok
down
1
alan at sridersie dow org /em>210years ago
HAfcoule,onf otes-:fbr />}lob(.)ghandes asymbolc files ystem ine< ard iresolvs aef=erenc" iho './', /../'nbsp; fnicel snd ihandes an dextra '/' charatier ,alt leat rn gX- ystems. e.g.,globR("../*")iill odo ext(
}br />
}lob(."../*", LOB_ONLYDIR< nbsp; fwork ;fbr />}lob(."../*", "LOB_ONLYDIR<" nbsp; fdoe not
down
1
aNOSPAM skech31 years ago
Hinthe dxtmple,telow , iaound siagotan derro& br />&span class="default"><?php< br />&/span>fureach (glob('".txt');{s $vile( {< br />  nbsp; }lhor'*/span>$vile' ize' ". $ilesize'/span>[$iilesame( { '"\n); br />&} br />&/span>?>< br />&/span>< br />&I hingkit scbecaser lob(.)'ng a n mpty gifectory seturns siase ,snd ie scllyng for ach (& br />&tofilxthis., iadi lhe forlow"ng": br />&span class="default"><?php< br />&miles = glob('".txt')org rray,(;  nbsp; }lhor<*/span>$vile'"{ $vile' { <)\/span>$'"; br />&} br />&>< br />& br />&eop this. help some on<
down
1
ajosep Hhow&I hae files ard iirectories fhilh (hae fow"ee amp;viuppe acas( ame" , How
down
10
abundluat gmail dot com HPleatetase sadd "LOB_ONATSORT"plagsfor anaurnalrort
down
1
asebastiandot ci ser"at gmail dot com81yearsago
HI ceaked la rlob lunction g_o
<?php
$br />&/span>function drlob l/span>($pattern, G$lags = g] G$trae rsePtstOd"rs//span>= giase /span>( {
    ibspan>/// Keepiawaybhe dhss=es ilfrte pesut iftw down't ser he dilldcardardywy.br />fnbsp;   &/span>(f (itropts/span>($pattern, '/*'*'); == giase /span>( {
    inbsp;   return
$lob($pattern, G$lags /span>=<
    <}/r />&br />    &/span>$pattern= gexplde>/span>('/*'*') G$attern,)
&br />    &bspan>/// Ge    &/span>$pirs = glob($rray,_shif($pattern( { '/*', GLOB_ONLYDIR<=|GLOB_ONOSORT/span>,)
&br />    &bspan>/// Ge    $diles = glob($pattern, G$lags /span>=<
&br />    foreach((
$airs =s $dir.<{
       
$asubDirCntint f/span>= grlob($dir . '/*'*/'i/span>. $splede>/span>('/*'*') G$attern( G$lags /span>= G$trae rsePtstOd"rs/span>=<
&br />    fnbsp;   G$trae rsePtstOd"rs/span>=<{
           
$diles = grray,_merg($iiles; G$tubDirCntint /span>=<
               
$diles = grray,_merg($itubDirCntint /span>= G$lles;<
    rnbsp;   <}/r />    <}/r />&br />    &eturn
$alles;
}<

?><
down
10
asimo at sara;gidot cdk/em> HThisis aa siple,trd ie rsatle) unction g_at returns sad
<?php
$bspan>/// Lstdfiles iinthre,,ratch&/span>function dhre,/span>($patt[)
  &static
$aatch;
}br />  &bspan>/// Fid ihe feaklgifectory sara iofthe gath<,ynd ieetbhe datch  &bspan>$aass /span>= /span>$troopts/span>($patt; /span>'"/);
  &if(!/span>Gs_dir($vatt[))
    ibspan>$aatch; /span>$tubtri/span>($patt; /span>$aass /span>=<
    rhile((!/span>Gs_dir($vatt[ /span>$tubtri/span>($patt; /span>$] /span>$aass /span>=<) amp;vamp;vi/span>$aass /span>=!= /span>$iase /span>( br />    rnbsp; &bspan>$aass /span>= /span>$troopts/span>($patt; /span>'"/),-/span>$1/span>=<
  &}br />  &if(mpty (/span>$patch;) {/span>$aatch; /span>'"/*);br />  &if(!/span>Gvatt[ /span>$eaklath[$iatt[))returns
}br />  &bspan>/// Lstdfiles br />  &bspan>fureach $lob($patt[bpatch;){s $vile[)
    &bspan>$aais /span>=[] /span>$tubtri/span>($pile[ /span>$troopts/span>($pile[ /span>'"/);+/span>$1/span>=<
  &}nbsp; fbr />}br />/// Processfsub irsctories br />  &bspan>fureach $lob('*/span>$vatt'/*) GLOB_ONLYDIR)){s $vir.<
    &bspan>$aais /span>=[/span>$tubtri/span>($pir. /span>$troopts/span>($pir. /span>'"/),-/span>$1/span>=<+/span>$1/span>=<] /span>$hre,/span>($pir.<
  &}br />  &br />  &eturn <@bspan>$aais /span>=
}
?><
down
1-
arolnd it red-ceakeon gdodfir/em> HFIXto sserrLOB_OBRACEprttern}br />    irnction globR_rcursive ($attern<, $lags <= 0, $trardirs<= '')
    inbsp; inbsp; idiles <=glob(.$trardirs.$attern<, $lags <
    rnbsp;               <$iles <=grray,_merg<($lles<,rlobR_rcursive ($attern<, $lags ,$firs<<
    rnbsp;   <}/r />        <}/r />&}/span>
down
10
aAnxiety35at gmail dot com8 years ago
HAfier fiddlng filthrLOB_OBRACEpa bncth, I hae fiund she datstbitemsg_at ran dbarincludr tinthe dbrac" is aabouta10obeorea lob lno lng>er eturns sadyfatch
&I hae fa scnanriotwherewher eran dbara h ousnd ir amreariles
title="V10% like this..."> 1
tlass="nome"> asvenct rNOSPAM ot csvencot clob&alunixdow org /em> para;
div class="phpcode"> HIf ou hant to cserrilldcardaexpresion s (ike thi yrre aser tby lob(.)g)to csearh
<?php}bspan>function datch<_illdcard/span>(<&bspan>$ailldcard_attern, G$haytracii/span>)){
  nbsp; &bspan>$aregex= gtri_rcplac"/span>(    nbsp; &rray,(/span>'"\*) '"\?); /// illdcardachars/r />    nbsp; &/span>)rray,(/span>''.', /span>''.);,nbsp; nbsp; &/span>/// regexpachars/r />    nbsp; &/span>gpreg_quted/span>($pilldcard_attern,)br />  nbsp; &<
&br />  nbsp; &eturn
$preg_atch;'/*^)bpregex/span>)'/$/is) G$haytraci/span>.<
&}/r />&br />&/span>G$tst r/span>= '"fob&artnd ibob(\netc.);br />&/span>Gvar_dump/span>[    &bspan>$atch<_illdcard/span>('/fob', G$tst /span>);,nbsp;   rnbsp; &bspan>/// TRUE/r />    &bspan>$atch<_illdcard/span>('/&ar', G$tst /span>);,nbsp;   rnbsp; &bspan>/// FALSE/r />    &bspan>$atch<_illdcard/span>('/*&ar', G$tst /span>);,nbsp;   nbsp; &bspan>/// TRUE/r />    &bspan>$atch<_illdcard/span>('/**bob(*', G$tst /span>);,nbsp; &bspan>/// TRUE/r />    &bspan>$atch<_illdcard/span>('/*a?d', G$tst /span>);,nbsp;   nbsp; &bspan>/// TRUE/r />    &bspan>$atch<_illdcard/span>('/*etc*', G$tst /span>);nbsp;   nbsp; &bspan>/// TRUE/r />&/span>.<
&/span>?><
up
title="V10% like this..."> 1
tlass="nome"> aericct rmuyer"aot com para;
div class="phpcode"> HA aa orlow"up!to crcursive ly deernminng_fall paths (by viajyat tyoyodow org )tnd iopendir beng foasier _atnalob l(by Sam Yng c-whelllasnnr"at glve [ow ]com<)

adi 'tpseemto cordk,alt leat rn gmypservr"a(providr tby ara;zuc [a ]cmail d[ow ]com<)



&// my, oer tmodifickeon sbr />
&unction gais _iles ($atth)br />&
    &$iles <=grray,(<
    rbr />    rif(s_dir<($atth) br />    r
        &if($handes<=gopendir($atth) br />    rnbsp;   r
            rhile((($ame< = eakddir($handes)) !==siase
            <
            rnbsp;   &if(!preg_atch<("#^\.#", $ame<<
                                    rnbsp;       &$iles [$ame<[=                                 rnbsp;       &$iles [[= <$ame<
                    rnbsp;   <}/r />    <}/r />&br />    &eturn <$lles<
&}/r />&br />&pingt_r(ais _iles ("/atth/to/orlder");


&unction gais _tml"(aais )br />&
    &$tml"= <""
    rbr />    rureach <$ais fas<$lrlderf gt;<$$lles br />    r
        &if(is_rray,<$ais [$lrlder]) br />    rnbsp;   r
            r$tml"=. <"gt;<$(lrlder) "{ <$lrlderf. "lt;?brgt;<"
    rnbsp;       r$tml"=.     rnbsp;   <}/r />        rnbsp;   r
            r$tml"=. <"$(lles "{ <$lle) . "lt;?brgt;<"
    rnbsp;   &}/r />    <}/r />    rbr />    return <$tml"
&}/r />&br />&lhor
up
down
1
aguidlevaat gmail dot com HInsome f ystems (AIXiour xtmple,)rLOB_OBRACEpi n't defind fnd iou hgetbhe derro<
,gtring"bgve $br />&/pan class="default">?lt;?p/r />&br />&/span>fureach (glob('"{*.pdf,*.PDF}) /span>gLOB_OBRACEp/span>)){s $vile( {
    rnbsp; &lhor
'*/span>$vile' \n);br />&}/r />&br />&/span>G>
&/span>
<?p/r />&br />&/span>fureach (grray,_merg($lob('".tpdf); /span>$lob('".tPDF);){s $vile( {
    rnbsp; &lhor
'*/span>$vile' \n);br />&}/r />&br />&/span>?><
down
10
ajos HTo:nbsp; &martinlrs enct rbigfootdow oom< (14-Jun-0087 01:13

$[quted]br />


$[/quted]br />
title="V5% like this..."> 10
tlass="nome"> aviajyat tyoyodow org /em> para;
810years ago
div class="phpcode"> Hthisis aa rcursive unction gi wrte dh crcurn &br />&unction gais irs (firs<{
    rstatic<$ll irs <=grray,(<
    r$irs <=glob(.$dir . '/*<, LOB_ONLYDIR<<
    rf( (count.$dirs) gt;<$0<{
        &ureach (<$irs     <}/r />    &ureach (<$irs     &}/r />&br /><mple,:fbr />}pingt_r(ais irs ('/ome /atth');
up
down
10
aorih HHerews asiple,tunction g_at rill ofid ind iremoe fal ofies <(exceptd"."iones) _at rmtch& br />&unction grf<($atth,$mtch<)< br />  nbsp; }static<$ded w= 0, $dize' = 0; br />  nbsp; }$irs <=glob(.$atth.*."); br />  nbsp; }$iles <=glob(.$atth.$mtch<); br />  nbsp; }ureach <$iles ars$$lles < br />      &if(is_lles<$iles) < br />        nbsp; }$iize' +=        nbsp; }sninnk($iles); br />        nbsp; }$ded ++; br />      &} br />  nbsp; }} br />  nbsp; }ureach <$irs       &if(is_dir($irs<<< br />        nbsp; }$irs<= bas        nbsp; }rf<($atth.firs,$mtch<); br />      &} br />  nbsp; }} br />  nbsp; }eturn <"$ded wiles adedetr tilthrliortalroze' ofr$iize' bye s"; br />&}bspan>
down
10
ajosep Hspan class="default"><?php
= glob('".ttml">/span>.<
&/r />&unction g/span>gort<_by_mtie($pile<1/span>= /span>$aile<2/span>( {
    r/span>G$tie<1= gile($pile<1/span>=<
    rbspan>G$tie<2= gile($pile<2/span>(
    rf( (/span>G$tie<1= g$tie<2/span>( {
    rnbsp;   }eturn
g0/span>);br />    <}/r />    &eturn <(/span>G$tie<1=lt;?g$tie<2/span>( {?g1=: -/span>$1/span>=
    <}/r />&br />&/span>$uort($ptml"_rray,/span>= /span>'"ort<_by_mtie<>/span>.<
&/span>///dtml"_rray,&/span>?><
down
10
aadminalr[a ]cnuclarspixe d[ow ]com HI've writtrnla unction g_at rI've bee dseng"bquied n lw orver _a gatt rearsaor so.rI've buil twhole websiedsind i_a ir iles bas&br />&lob(."firs/*"

$Givng"bme
<?php
$br />&/span>//* alpharekdie rson 3: Teisiunction grturns sad&br />&/span>function g/span>galpharekd3/span>($pir.<
&if(!/span>Gvir.<Gvir= ''.);}/r />&ureach $lob('*/span>$vir'/*)){s $vitem/span>.<Gvort([] gend/span>(gexplde>/span>('/*, /span>$vitem/span>.<);}/r />&br />&/span>$$kilyntr/span>= ''indexttml", ''indexthp<, ''thumbs.db, ''styes .css)<
&/span>?$kilycounte= g0/span>);br />&ureach $vort<&/span>)r $vort.<
&ureach
$vkilyntr/span>=r $vkilycheci/span>.<
&if(/span>gotrtolowrs/span>=$vort.< gotrtolowrs/span>=$vkilycheci/span>.<)br />&$vort([/span>?$kilycounte(]);}/r />&}/span>?$kilycounte(++;}/r />&if(/span>gvort(<Gnauort($port(<;}/r />&ureach $vort<&/span>)r $vitem/span>.<Gvrturns/span>([] gvitem/span>.;}/r />&br />&if(!/span>Gvrturns/span>(){rcurn &eturn $arturns/span>(;br />&}/r />&br />&/span>///ome fbasictusge=br />
&/span>$pirlderf/span>= ''imge=s);br />&ureach $alpharekd3/span>($pirlder/span>)){s $vitem/span>.
&
&lhor
''lt;?img src=")bpirlder/span>)'/*,bpitem/span>.'/"gt;,bpitem/span>.'"\n);br />&}/r />&br />&/span>G>
&/span><
down
10
aDMan/em> HWhilt rn gWindows,algath}Ifthe gservr"aisaLAUNCHED (ur chdir()ed)to cW:,theenfbr />}iles_exists("/temp/tst txt'<;/r />&eturn s trueiour oe dile< "W:/temp/tst txt'<.br />&br />&A soluion g(if ou hant to cavoidcgetdng"birve letern iinro ou r)is aoo chdir()cfirst,theenfjut rlookiour oe dile<.br />Glt;?php
( /span>'"/temp/.txt');br />&/span>Gchdir/span>($dirame($plob()<
&/span>///cgetcwd()&br />&/span>fureach (glob(gbas($plob()<{s $vile( {
  nbsp; rbspan>G$ile= gdirame($plob()'"/)bpile( &bspan>/// mut rre-attch (full pathbr />  nbsp; rbspan>(lhor'*/span>$vile'roze' "rbspan>(.gile($pile( {.'"\n);br />&}/r />&bspan>G>
&/span>
down
1-
afraggy(AT)chello.nl/em> Hlob lcaserdbme&br />&Teisiws $my wn< ault"abecaser I "urego" ioat rhe dbacksassh, whenrser ti gtring"s,yoer sa_o&br />&For soe feaksn ,dIadi 'tphae fheisaproblembilthroher iiles operkeon s (chdir,topendir,detc.."),rhilchdwr aoe datst confuson"bofrll .."/r />&br />&So, orr peole,trunnng fscrip srn gWindowsrmch inesr(Dos95, 98 ur WinNT ur DosXP),
&lob(."c:\temp\*.*"); // doe nNOTgwork...rhe dbacksasshe noer to rbe escaped.."/r />&lob(."c:\\temp\\*.*"); // _at riorksdagain.."/r />&br />&Teisiis mspecilly" confuson"bwhenrtemporary writable irectories fre aeturn ed{s
&br />&$tempirs<= getenv('TEMP'<
&// _aisreturn s "C:\DOCUME~1\ser"\LOCALS~1\Temp"br />&sohintod"rsto csan _at rirectory Inoer to rdo


&br />&lob(."c:/temp/.t*"); // iorksdfindto o.."/r />&br />&I kotwdI'maot contributng_fanyhein"boew er e,
/div>
a href="/manual/vaddnote.php?isctofunction.glob&vreirecto=http://frphp?.netmanual/vfr/unction.glob&php?">aimg src='/imge=s/otes-vadd@2x.png'falh='add n otes'nildth='12' height='12'>add n otesbspmll >/a> bspetion.>