Tuesday, August 12, 2008

Getting a recursive file list in PHP: Code Example

Ever wonder how you can get an array of files in a directory. ALL the files, including those in the subfolders? Sure you can do that! an example is shown below! The function below returns an array tree of files. It recursively get files in a folder, then calls itself again for all the sub folders.

function dirfiles($dirname = '.', $relative = false) {
if($dirname == ''){$dirname = '.';}
if (!is_dir($dirname) || !is_readable($dirname)) {
// check whether the directory is valid.
return false;
}

$a = array();

$handle = opendir($dirname);
while (false !== ($file = readdir($handle))) {
if ($file != '.' && $file != '..' && is_readable($dirname . DIRECTORY_SEPARATOR . $file)) {
if (is_dir($dirname . DIRECTORY_SEPARATOR . $file)) {
$a[($relative ? $file : $dirname . DIRECTORY_SEPARATOR . $file)] = dirfiles($dirname . DIRECTORY_SEPARATOR . $file, $relative);
}else{
$a[] = ($relative ? $file : $dirname . DIRECTORY_SEPARATOR . $file);
}
}
}
closedir($handle);

return $a;
}


You can specify whether to return each array in an relative manner or not.

$relative = true:
Array
(
[data] => Array
(
[0] => dataone.inc.php
[1] => user.inc.php
[2] => forum.inc.php
)

[0] => constants.inc.php
[1] => functions.inc.php
[2] => header.inc.php
)


$relative = false:

Array
(
[dat/inc/data] => Array
(
[0] => dat/inc/datadataone.inc.php
[1] => dat/inc/datauser.inc.php
[2] => dat/inc/dataforum.inc.php
)

[0] => dat/inc/constants.inc.php
[1] => dat/inc/functions.inc.php
[2] => dat/inc/header.inc.php
)

For ($relative = true), the presentation would be nicer, however in ($relative = false), the array would be more useful for argument of another file access function.

hope it is useful ^^

Link to code example on pastebin: http://thephpcode.pastebin.com/f495b59a1

2 comments:

Brilliant Media said...

Looks nice, but it would be good to see an actual example of how to call the function.. I have tried all kinds of calls, and all I get is an empty screen!

subbu raj said...

Excellent php code examples. Thanks for sharing.

PHP Development Company