001<?php 002 003/* 004 005scan_directory_recursively( directory to scan, filter ) 006expects path to directory and optional an extension to filter 007of course PHP has to have the permissions to read the directory 008you specify and all files and folders inside this directory 009 010*/ 011 012functionscan_directory_recursively($directory,$filter=FALSE) 013{ 014// if the path has a slash at the end we remove it here 015if(substr($directory,-1)=='/') 016{ 017$directory=substr($directory,0,-1); 018} 019 020// if the path is not valid or is not a directory ... 021if(!file_exists($directory)||!is_dir($directory)) 022{ 023// ... we return false and exit the function 024returnFALSE; 025 026// ... else if the path is readable 027}elseif(is_readable($directory)) 028{ 029// we open the directory 030$directory_list=opendir($directory); 031 032// and scan through the items inside 033while(FALSE!==($file=readdir($directory_list))) 034{ 035// if the filepointer is not the current directory 036// or the parent directory 037if($file!='.'&&$file!='..') 038{ 039// we build the new path to scan 040$path=$directory.'/'.$file; 041 042// if the path is readable 043if(is_readable($path)) 044{ 045// we split the new path by directories 046$subdirectories=explode('/',$path); 047 048// if the new path is a directory 049if(is_dir($path)) 050{ 051// add the directory details to the file list 052$directory_tree[]=array( 053'path'=>$path, 054'name'=>end($subdirectories), 055'kind'=>'directory', 056 057// we scan the new path by calling this function 058'content'=>scan_directory_recursively($path,$filter)); 059 060// if the new path is a file 061}elseif(is_file($path)) 062{ 063// get the file extension by taking everything after the last dot 064$extension=end(explode('.',end($subdirectories))); 065 066// if there is no filter set or the filter is set and matches 067if($filter===FALSE||$filter==$extension) 068{ 069// add the file details to the file list 070$directory_tree[]=array( 071'path'=>$path, 072'name'=>end($subdirectories), 073'extension'=>$extension, 074'size'=>filesize($path), 075'kind'=>'file'); 076} 077} 078} 079} 080} 081// close the directory 082closedir($directory_list); 083 084// return file list 085return$directory_tree; 086 087// if the path is not readable ... 088}else{ 089// ... we return false 090returnFALSE; 091} 092} 093 094// to use this function to get all files and directories in an array, write: 095// $filestructure = scan_directory_recursively('path/to/directory'); 096 097// to use this function to scan a directory and filter the results, write: 098// $fileselection = scan_directory_recursively('directory', 'extension'); 099 100// example 101echo'<pre>'; 102print_r(scan_directory_recursively('.')); 103echo'</pre>'; 104 105?>