Reading Directories

Method 1: Using opendir(), readdir() and closedir()

 

  1. Assign the required directory to a handler variable: $dirHandle = opendir('path/to/target') ;
  2. Read the contents of the directory using readdir()
  3. Close the directory variable handler using closedir()
<?php
    $handle = opendir('/path/to/directory') ;

    if ($handle) {
        while (false !== ($file = readdir($handle))) {
            print "$file<br />\n";
        }
        closedir($handle);
    }
?>

readdir() returns the file name of the next file in the directory in the order stored by the file system. This will remain TRUE until the end of the directory is reached, at which point it will turn FALSE and the while loop will end

 

 

Method 2: using scandir()

 

scandir() returns an array of the contents of the specified directory

 

<?php
	$myDir = scandir("./") ;

	foreach($myDir as $value) {

		echo "$value <br>" ;
	}
?>

Leave a Reply