dir

Description

A pseudo-object oriented mechanism for reading a directory. The
given directory is opened.

Parameters

directory

Directory to open

context

Note: Context support was added
with PHP 5.0.0. For a description of contexts, refer to
Streams.

Return Values

Returns an instance of Directory, or NULL with
wrong parameters, or FALSE in case of another error.

Examples

Example #1 dir() example

Please note the fashion in which Directory::read()'s
return value is checked in the example below. We are explicitly
testing whether the return value is identical to (equal to and of
the same type as - see
Comparison Operators for more information) FALSE since
otherwise, any directory entry whose name evaluates to FALSE will
stop the loop.

This one's pretty nice. After getting frustrated for hunting down .jpg files in my massive music collection (PHP would run out of memory), I thought there should be a preg_ls function.

function preg_ls ($path=".", $rec=false, $pat="/.*/") { // it's going to be used repeatedly, ensure we compile it for speed. $pat=preg_replace("|(/.*/[^S]*)|s", "\\1S", $pat); //Remove trailing slashes from path while (substr($path,-1,1)=="/") $path=substr($path,0,-1); //also, make sure that $path is a directory and repair any screwups if (!is_dir($path)) $path=dirname($path); //assert either truth or falsehoold of $rec, allow no scalars to mean truth if ($rec!==true) $rec=false; //get a directory handle $d=dir($path); //initialise the output array $ret=Array(); //loop, reading until there's no more to read while (false!==($e=$d->read())) { //Ignore parent- and self-links if (($e==".")||($e=="..")) continue; //If we're working recursively and it's a directory, grab and merge if ($rec && is_dir($path."/".$e)) { $ret=array_merge($ret,preg_ls($path."/".$e,$rec,$pat)); continue; } //If it don't match, exclude it if (!preg_match($pat,$e)) continue; //In all other cases, add it to the output array $ret[]=$path."/".$e; } //finally, return the array return $ret;}

The dir Class, from what I can tell, on a Windows box is not a live image of the directory. When the class is instantiated it takes a snapshot of the directory and then the iterator works off that.

I may be wrong, but when I run two processes that look to see if a directory exists, and then deletes the dir when some processing takes place. Deletes from one process do not effect the iteration of the second.

To get around this I check that the file exists before doing my processing:

Regarding samuel's comment about the dir() function not supporting Unicode properly, it's all in the encoding. The function does NOT internally change Unicode characters into question marks (?), as I was first led to believe. If you simply try to output them in UTF-8, they'll show up just right.