PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  
<dio_writechdir>
view the version of this page
Last updated: Thu, 21 Aug 2003

XXIII. Directory functions

Introduction

Requirements

No external libraries are needed to build this extension.

Installation

There is no installation needed to use these functions; they are part of the PHP core.

Runtime Configuration

This extension has no configuration directives defined in php.ini.

Resource Types

Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

DIRECTORY_SEPARATOR (string)

PATH_SEPARATOR (string)

See Also

For related functions such as dirname(), is_dir(), mkdir(), and rmdir(), see the Filesystem section.

Table of Contents
chdir -- Change directory
chroot -- Change the root directory
dir -- directory class
closedir -- close directory handle
getcwd -- gets the current working directory
opendir -- open directory handle
readdir -- read entry from directory handle
rewinddir -- rewind directory handle
scandir --  List files and directories inside the specified path


add a note add a note User Contributed Notes
Directory functions
11-Oct-2003 05:12
get a list of files and directories recursivelly without the use of global variables.
the difference between this one and piccaso at gmx dot net's, is that this one returns files inside the subdirectories as well (with full path) :

function recursive_listdir($base) {
    static $filelist = array();
    static $dirlist = array();

    if(is_dir($base)) {
       $dh = opendir($base);
       while (false !== ($dir = readdir($dh))) {
           if (is_dir($base ."/". $dir) && $dir !== '.' && $dir !== '..') {
                $subbase = $base ."/". $dir;
                $dirlist[] = $subbase;
                $subdirlist = recursive_listdir($subbase);
            } elseif(is_file($base ."/". $dir) && $dir !== '.' && $dir !== '..') {
                $filelist[] = $base ."/". $dir;
            }
        }
        closedir($dh);
    }
    $array['dirs'] = $dirlist;
    $array['files'] = $filelist;
    return $array;
 }
arun at upress dot unm dot edu
09-Oct-2003 05:34
correction to piccaso at gmx dot net's

function recrusive_dirlist($base_dir)
<?
/*
This function retuns all directory and file names from the given directory.
Works recrusive. Based on ltena at gmx dot net's function.
*/
function recrusive_dirlist($base_dir)
{
global 
$getDirList_alldirs,$getDirList_allfiles;
    function 
getDirList($base)
    {
    global 
$getDirList_alldirs,$getDirList_allfiles;
    if(
is_dir($base))
        {
           
$dh opendir($base);
        while (
false !== ($dir readdir($dh)))
            {
            if (
is_dir($base ."/"$dir) && $dir !== '.' && $dir !== '..'//note the change in this line
               
{
                   
$subs $dir    ;
                   
$subbase $base ."/"$dir;//note the change in this line
                   
$getDirList_alldirs[]=$subbase;
                   
getDirList($subbase);
                }
            elseif(
is_file($base ."/"$dir) && $dir !== '.' && $dir !== '..')//change in this line too
               
{
               
$getDirList_allfiles[]=$base ."/"$dir;//change in this line too
               
}
            }
           
closedir($dh);
        }
    }

getDirList($base_dir);
$retval['dirs']=$getDirList_alldirs;
$retval['files']=$getDirList_allfiles;
return 
$retval;
}

// example usage:
echo '<pre>';
print_r(recrusive_dirlist('/home/computerdreams.at/cms/'));
echo 
'</pre>';
/*
Prints out something like this:

Array
(
    [dirs] => Array
        (
            [0] => /home/computerdreams.at/cms/xoops-2.0.3/
            [1] => /home/computerdreams.at/cms/xoops-2.0.3/html/
            [2] => /home/computerdreams.at/cms/xoops-2.0.3/html/modules/
            [3] => /home/computerdreams.at/cms/xoops-2.0.3/html/modules/news/
            ...
            ...
        )

    [files] => Array
        (
            [0] => /home/computerdreams.at/cms/li
            [1] => /home/computerdreams.at/cms/lo
            [2] => /home/computerdreams.at/cms/tab
            [3] => /home/computerdreams.at/cms/tmp
            ...
            ...
        )

)

I downt know if this is the best way to do this.
If you find a better way, please drop me a note.

greez
piccaso@gmx.net
*/
?>

I used the function without making any changes and did not get any output, no error though. then i realised the mistake and did the changes and got perfect output.

hope this helps someone in future.

Arun.
piccaso at gmx dot net
08-Sep-2003 02:17
<?
/*
This function retuns all directory and file names from the given directory.
Works recrusive. Based on ltena at gmx dot net's function.
*/
function recrusive_dirlist($base_dir)
{
global 
$getDirList_alldirs,$getDirList_allfiles;
    function 
getDirList($base)
    {
    global 
$getDirList_alldirs,$getDirList_allfiles;
    if(
is_dir($base))
        {
           
$dh opendir($base);
        while (
false !== ($dir readdir($dh))) 
            {
            if (
is_dir($base $dir) && $dir !== '.' && $dir !== '..'
                {
                   
$subs $dir    ;
                   
$subbase $base $dir '/';
                   
$getDirList_alldirs[]=$subbase;
                   
getDirList($subbase);
                } 
            elseif(
is_file($base $dir) && $dir !== '.' && $dir !== '..')
                {
               
$getDirList_allfiles[]=$base $dir;
                }
            }
           
closedir($dh);
        }
    }

getDirList($base_dir); 
$retval['dirs']=$getDirList_alldirs;
$retval['files']=$getDirList_allfiles;
return 
$retval;
}

// example usage:
echo '<pre>';
print_r(recrusive_dirlist('/home/computerdreams.at/cms/'));
echo 
'</pre>';
/*
Prints out something like this:

Array
(
    [dirs] => Array
        (
            [0] => /home/computerdreams.at/cms/xoops-2.0.3/
            [1] => /home/computerdreams.at/cms/xoops-2.0.3/html/
            [2] => /home/computerdreams.at/cms/xoops-2.0.3/html/modules/
            [3] => /home/computerdreams.at/cms/xoops-2.0.3/html/modules/news/
            ...
            ...
        )

    [files] => Array
        (
            [0] => /home/computerdreams.at/cms/li
            [1] => /home/computerdreams.at/cms/lo
            [2] => /home/computerdreams.at/cms/tab
            [3] => /home/computerdreams.at/cms/tmp
            ...
            ...
        )

)

I downt know if this is the best way to do this.
If you find a better way, please drop me a note.

greez
piccaso@gmx.net
*/
?>
de \ kibo \ niels
27-Aug-2003 09:53
Why, here's the millionth recursive directory listing script. The extra added bonus in this thing is, it lists the directories in a win-explorer-like fashion, with indentation according to hierarchical depth and such gizmos.

Using the variable $sf, you can control whether files should be displayed. If $sf == 0, only directories will be shown. This is useful if you just want to see the hierarchical structure of what's in that path.

The output must be encapsulated in "preformatted" tags, otherwise things will look wild. Directories are shown in "bold", the explorer-like watchamacallits that show you where you are, are "italic", so you'd best use CSS to overwrite the standard formatting so it looks good. I used this:
b {color:blue}
i {font-style:normal; color:gray}

This code can of course be greatly improved upon *hint* :)

<php?
function displaydir ($path, $depth) {
    if (($d = @opendir ($path)) === false) echo ('[Could not open path:]');
    else {
        while ($f = readdir ($d)) {
            if ($f != "." && $f != "..") {
                if (is_dir ($path . "/" . $f)) {
                    for ($i = 0; $i < $depth - 1; $i++) echo '<i>| </i>';
                    echo '<i>+-</i>';
                    echo "<b>$f</b>\n";
                    $depth++;
                    displaydir ($path . "/" . $f, $depth);
                    $depth--;
                } else {
                    if ($sf == 1) {
                        for ($i = 0; $i < $depth - 1; $i++) echo '<i>| </i>';
                        echo '<i>+-</i>';
                        echo "$f\n";
                    }
                }
            }
        }
        closedir ($d);
    }
}

displaydir ($url, 0);
?>
ltena at gmx dot net
24-Jul-2003 06:36
Recursive function to browse folders (Unix)

$base = '/home/';

function getDirList($base)
{
    if(is_dir($base)){
        $dh = opendir($base);
        while (false !== ($dir = readdir($dh))) {
            if (is_dir($base . $dir) && $dir !== '.' && $dir !== '..') {
                $subs = $dir    ;
                $subbase = $base . $dir . '/';
                print $subbase . "<br>";
                getDirList($subbase);
            } else {
                next;
            }
        }
        closedir($dh);
    } else {
        print "no es dir";
    }
}

getDirList($base);

Regards
Luis Tena O.
Mexico City
fabrizio - > effepi.system at inwind.it
21-May-2003 11:39
here a function that create an array with all the files and
 folders in the directory and in all the subdirectories

qui una funzione che crea un array con tutti i file e le cartelle
 nella directory ricercata e nelle sue subdirectories

i.e.:
dir1
 |-dir2
 |   |-file1
 |   |-dir3
 |-file2

$array[dir1][dir2][0] = file1
$array[dir1][dir2][dir3]=NULL  //no files inside
$array[dir1][0] = file2

function expFp($folder = ".", $filetype = "")
    {
    $currdir=getcwd();
    if ($folder)
        @chdir("$folder");
    $dh = opendir(".");
     while(false !== ($file = readdir($dh)))
        {
        // insert all the files in an array
        if(is_file($file) &&
             ( strtoupper( substr( $file,(-1*strlen($filetype))))==strtoupper($filetype)))   
            $a_files[] = $file;
        //htm is a folder that you don't want to use
        if (is_dir($file) && $file!="." && $file!=".." && $file!="htm")
            $a_files[$file] = expFp($file, $filetype);
        }
    closedir($dh);
    chdir($currdir);
//    if (is_array($a_files))
//        array_multisort($a_files);
    return $a_files;
    }
johnpipi at hotmail dot com
03-Mar-2003 02:22
Here is a function that returns an array of all files (filenames) from inputted directory.

   function getDirFiles($dirPath)
   {
      if ($handle = opendir($dirPath))
      {
          while (false !== ($file = readdir($handle)))
              if ($file != "." && $file != "..")
                  $filesArr[] = trim($file);
                 
          closedir($handle);
      } 
     
      return $filesArr;    
   }
admin[ at T]networkessence dot net
21-Aug-2002 07:41
This script will count lines of code that do not begin with // or are not blank space.  It's very approximate because it will include /* */ comments and will also include lines that start with blank space and then //.  It's a start though (it's recursive, so don't use this with a directory structure that includes symbolic links).  This will recursively count all the lines of files that end with .php.  You can change .php to whatever, and also change the guidelines as to whether a line qualifies as a comment or not (look around the !="//" part)

$i=0;

function getDirList ($dirName) {
        global $i;
        $d = dir($dirName);
                while($entry = $d->read()) {
                        if ($entry != "." && $entry != "..") {
                                if (is_dir($dirName."/".$entry)) {
                                        getDirList($dirName."/".$entry);
                                } else if(substr($entry, -4)=='.php') {
                                        if($read_file = file($dirName.'/'.$entry))
                                                foreach($read_file as $line)
                                                        if(($line!="\n") && (substr($line, 0, 2)!="//"))
                                                                $i++;
                                        echo $dirName."/".$entry."\n";
                                }
                        }
                }
        $d->close();
}

getDirList("./path/to/files");

echo $i;
erere CHIOCCIOLINA iname PUNTO com
17-Aug-2002 08:40
In fancao0515@0451.com's function list_dir($dirname):

if(is_dir($dirname.$file))
list_dir($dirname.$file.'\\');

should become:

if(is_dir($dirname.$file))
$result_array[]=list_dir($dirname.$file.'\\');

or recursion will be done, but no subdirs will be pushed into the $result_array.

Ernesto
tapani
07-Aug-2002 08:54
shell_exec this

ls -la '$dir'|wc -l|sed 's/^ *//;'

to get number of files in dir
Bill at Example dot net
24-May-2002 02:20
Just a side note....not really php'ish

$mstrng = shell_exec('du -sc /usr/local/apache/www');
print "$mstrng";

Will get you the size of a directory, including all of its sub dirs and files within.
ben AT tech-space DOT net
24-May-2002 01:10
//lists all files in a directory with a given file name convention

function list_dir($file_name_convention) {
  switch ($file_name_convention) {
    case 'dated_reports':
      //matches files like '5_23_2002.html'
      $this_regexp = "/[0-9]{1,}_[0-9]{1,}_[0-9]{4,}/";
      break;
      //add more cases of file name conventions
  }
  $this_dir = dir('.');
  if ($this_regexp != null) {
    while ($file = $this_dir->read()) {
      if (preg_match($this_regexp, $file)) {
        $result_array[] = $file;
      }
    }
  }
  return $result_array;
}

<dio_writechdir>
 Last updated: Thu, 21 Aug 2003
show source | credits | sitemap | mirror sites 
Copyright © 2001-2003 The PHP Group
All rights reserved.
This mirror generously provided by: http://php.mirrors.ilisys.com.au/
Last updated: Sat 01 Nov 2003 04:13:36 EST EST