PHP

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

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

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.

Syntax

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

Example:

$files = scandir('/test');

print_r($files);

The above example output is:

Array
(
    [0] => .
    [1] => ..
    [2] => current.php
    [3] => forcast.txt
    [4] => sixthdir
)
by BrainBellupdated
Advertisement: