Jump to: navigation, search

Php dir

From w3cyberlearnings

Contents

PHP function dir

This is the object-oriented of directory handle of the directory class.

Syntax dir

dir is a directory to stream

dir(dir);

Return

Returns a directory stream on success or FALSE and an error on failure.

Note

Use @ infront of the function dir (@dir) to hide error output.

Example 1

<?php 
      $path = dirname(__FILE__).'/mydir';
      $dh = dir($path);
     
      
      while(false !== ($entry = $dh->read())) {
           echo $entry . "\n";
      }
      
      $dh->close();
?>

Output

learn.txt
a1
ac
a2
.
ab
..

Example 2: read directory recursively

<?php 
      function dirTree($dir) {
        $dh = dir($dir);
	$file = array();
        $subdirectory = array();

        while(false !==($entry = $dh->read())) {
	     if($entry != "." && $entry != "..") {
                 if(is_dir($dir.'/'. $entry)) {
                      $subdirectory  = dirTree($dir.'/'.$entry); // subdirectory
                      if(is_array($subdirectory)) {
			$file = array_merge($file,$subdirectory);
                      }
                 }
                 else {
                      array_push($file, $dir. '/'. $entry);
                 }
             }
        }
        $dh->close();
        return $file;
    }


    print_r(dirTree('mydir'));
?>


Output

Array
(
    [0] => mydir/learn.txt
    [1] => mydir/a1
    [2] => mydir/ac
    [3] => mydir/a2
    [4] => mydir/ab
    [5] => mydir/school/mark.txt
    [6] => mydir/school/great.txt
)

--chdir-- chroot-- closedir-- dir-- getcwd-- opendir-- readdir-- rewinddir-- scandir--

Navigation
Web
SQL
MISC
References