Browsing the File System

$d = dir('.');
while (false !== ($file = $d->read()))

Since PHP 3, PHP comes with a built-in class. This sounds strange because OOP (object-oriented programming) did not become "mainstream" in PHP before version 5; however, this special class offers several methods to access the file system. It is possible to get a list of all entries in a directory.

Reading a Directory's Contents with PHP's dir Class

  $d = dir('.');
  while (false !== ($file = $d->read())) {
    echo htmlspecialchars($file) . '<br />';

You instantiate the class without the keyword new, just by providing the desired path as a parameter. Then the method read() iterates through the list of entries. The preceding code does exactly this and prints out the contents of the current directory.

Note that the two directory entries . (current directory) and .. (parent directory, if you are not in the root directory) are printed out.

Reading a Directory's Contents with scandir

scandir() function list files and directories inside the specified path and returns an array of files and directories from the path/directory.


array scandir ( string $directory [, int $sorting_order = SCANDIR_SORT_ASCENDING [, resource $context ]] )

This function accepts three parameters:

  1. directory the target directory for scanning

  2. sorting_order to set sort order, default is alphabetical in ascending order, set SCANDIR_SORT_DESCENDING for descending order and SCANDIR_SORT_NONE for unsorted result.

  3. context


$files = scandir('/test');


The above example output is:

    [0] => .
    [1] => ..
    [2] => current.php
    [3] => forcast.txt
    [4] => sixthdir
by BrainBellupdated