User Contributed Notes: readdir
cjones@honors.montana.edu
27-Apr-1999 04:45
Note that this example won't work if there's a file named "0" in the directory! I just got bitten by this.
royapav@millsaps.edu
11-May-1999 05:08
To expand on the above user's comment, all file names after the "0" file will not be displayed, depending on the position of the "0" filename in the internal directory structure. Try the sample code in a test directory in which you created bogus files "foo", "bar", "0" and "baz" IN THAT ORDER.
Workaround:
while (($file = readdir($handle)) != "") {
Scripting is such fun, who needs strict typing ? :-)
25-Jun-1999 03:46
Why not make a dirArray (or something) that would return an array of directory entries? It'd be a lot easier to walk over...
ansinn@comcat.com
19-Aug-1999 07:32
Here's a quick code snippet that will load the directory data into an array.
function GetDirArray($sPath)
{
//Load Directory Into Array
$handle=opendir($sPath);
while ($file = readdir($handle))
$retVal[count($retVal)] = $file;
//Clean up and sort
closedir($handle);
sort($retVal);
return $retVal;
}
hendy@unics.cx
04-Nov-1999 09:05
hi,
is there a way i can sort the files in a directory by time ? (so most recent files are being printed first or last)
thank you for any suggestions
-hendy
invis98@yahoo.com
16-Dec-1999 12:18
Anyone have any ideas on how to seperate out/be able to tell directories from files?
srosenberger@cssi-tlo.com
30-Dec-1999 08:51
Above poster asked about how to seperate files from directories: Use the is_dir or is_file functions.
php@timewarp.org
05-Feb-2000 04:00
PHP 4b3 seems to require that you take the return of opendir(). You don't have to do anything with it, but it doesn't work otherwise.
opendir(".");
echo readdir();
echo readdir();
echo readdir();
will scream and die, while the following...
$foo=opendir(".");
echo readdir();
echo readdir();
echo readdir();
seems to work fine. Odd.
justin@fanetic.com
06-May-2000 12:10
Taking the GetDirArray() function above and adding some recurssion in to list the entire contents of a dir and the tree below:
function GetDirArray($sPath)
{
//Load Directory Into Array
$handle=opendir($sPath);
while ($file = readdir($handle))
{
$retVal[count($retVal)] = $file;
}
//Clean up and sort
closedir($handle);
sort($retVal);
//return $retVal;
while (list($key, $val) = each($retVal))
{
if ($val != "." && $val != "..")
{
$path = str_replace("//","/",$sPath.$val);
echo "$path ";
if (is_dir($sPath.$val))
{
GetDirArray($sPath.$val."/");
}
}
}
}