Monday 9 July 2012

List all mp3 files from a directory and its subdirectories using php.

Suppose you need to list all of your mp3 files from a folder and its all subfolders. Then this php script will help you.

Technique

  1. This function starts with a directory.
  2. And check for all the files and folder in it.
  3. If a folder found then this function call itself recursively.
  4. If its a file and its extension is .mp3 then print it.
function findfiles($directory,$xx) 
{
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($directory),
RecursiveIteratorIterator::SELF_FIRST);
foreach($iterator as $file) {

if($file->isDir()) {
findfiles($file->getRealpath(),$xx);
}
else{
if(strtolower(substr(basename($file),-3))=="mp3")
{
$xx.=basename($file);
}
}
}
return $xx;
}


Now just call the function



echo findfiles('./','');


Ok so when you need this?



Suppose you host your own music files and want to embed a music player that can play all of your music files. then you must list out all of your files into a folder and its subfolder and its subfolder ……… This script will list out all of your files. You have to modify this code for your purpose.