Getting the list of files in a folder
algis
Here is a nice recursive function that returns the list of files in a folder. If the folder contains subfolders, it will return the names with their relative path. Optionally you can supply a file type (extension) which you would like to consider, for example, return only .jpg or .php files.
function getDirListing( $dirName, $ext = '.php' ){
$dirLising = array();
$files = array();
$dirs = array();
if ! ( $handle = opendir($dirName) )
return $dirLising;
// read the folder file list
while ( false !== ($f = readdir($handle)) ){
// skip the dot pseudo folders
if( substr($f, 0, 1) == '.' )
continue;
// check if it is our extension
$thisExt = substr( $f, -strlen($ext) );
if ( ($ext == $thisExt) && ($f != basename(__FILE__)) )
$files[] = $f;
// subfolder? save for later recursive call
if( is_dir( $dirName . '/' . $f ) )
$dirs[] = $f;
}
closedir($handle);
$dirLising = $files;
// now go through subfolders if any
reset( $dirs );
foreach( $dirs as $d ){
$childListing = getDirListing( $dirName . '/' . $d );
foreach( $childListing as $childFile )
$dirLising[] = $d . '/' . $childFile;
}
sort( $dirLising );
return $dirLising;
}
Posted in PHP Application Development |