Sunday, April 25, 2010

PHP Listing all files in a folder and sub-folders

I was trying to write a php code that lists all files in a folder and sub folders tree.
At first I wrote this one
function printAll($dirName)
{
$handle=opendir($dirName);
while($file=readdir($handle)){
if(is_file($file)){
echo $file;
}
else if(is_dir($file)&&$file!='.' && $file!='..')//for excluding . and .. 
{
$dirName=$dirName.'/'.$file;
chdir($dirName);
printAll($dirName);
}//elseif
}
}
printAll(getcwd());//calling the function 

But it will list only the deepest files in the first subfolder tree.SO I searched php.net and got the solution. all the subfolder will be kept in a array and will be searched recursively. Here is the code
function printAll($dirName)
{
$dirs=array($dirName);
$files=array();
while($dir=array_pop($dirs)){
$handle=opendir($dir);
while($file=readdir($handle)){
if($file!='.' && $file!='..'){
$dest=$dir.'/'.$file;
if(is_file($dest)){
$files[]=$file;
echo $file;
}
else{
$dirs[]=$dest;
}
}
}//end of 1st while
}//end of 2nd while

return $files;
}//end of function

printAll(getcwd());
The function now returns a array containing the name all files in the current folder and subfolders tree.It will print all the file names too. you can easily modify this.
That's it! It was fun.If any function is unknown to you just visit php.net.

About Me

Web Developer From Dhaka, Bangladesh.