Zend - The PHP Company




Files and Directories

Add Code


Directory Recursion  

Type: code fragment
Added by: kuzb
Entered: 23/12/2001
Last modified: 01/12/2001
Rating: - (fewer than 3 votes)
Views: 9118
This handy little function will, given a starting directory, return an array of directories contained within the original directory. It does this by using recursion, a process by which a function calls itself repeatadly, until all conditions are met. Syntax is Array RecurseDir (string starting_directory)


<?php
function RecurseDir($basedir$AllDirectories=array()) {
        
#Create array for current directories contents
        
$ThisDir=array();
        
#switch to the directory we wish to scan
        
chdir($basedir);
        
$current=getcwd();
        
#open current directory for reading
        
$handle=opendir(".");
        while (
$file readdir($handle)) {
                
#Don't add special directories '..' or '.' to the list
                
if (($file!='..') & ($file!='.')) {
                        if (
is_dir($file)) {
                                
#build an array of contents for this directory
                                
array_push($ThisDir,$current.'/'.$file);
                        }
                }
        }
        
closedir($handle);
        
#Loop through each directory,  run RecurseDir function on each one
        
foreach ($ThisDir as $key=>$var) {
                
array_push($AllDirectories$var);
                
$AllDirectories=RecurseDir($var$AllDirectories);
        }
        
#make sure we go back to our origin
        
chdir($basedir);
        return 
$AllDirectories;
}
?>


Usage Example


<?
$dirlist
=RecurseDir("/home/ben");
foreach (
$dirlist as $key=>$val) {
    echo 
$val;
}
?>


Rate This Script





Search



This Category All Categories