scandir

(PHP 5)

scandir --  List files and directories inside the specified path

Description

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

Returns an array of files and directories from the directory. If directory is not a directory, then boolean FALSE is returned, and an error of level E_WARNING is generated.

By default, the sorted order is alphabetical in ascending order. If the optional sorting_order is used (set to 1), then sort order is alphabetical in descending order.

For a description of the context parameter, refer to Reference CXV, Stream Functions.

Note: Context support was added with PHP 5.0.0.

Example 1. A simple scandir() example

<?php
$dir    
= '/tmp';
$files1 = scandir($dir);
$files2 = scandir($dir, 1);

print_r($files1);
print_r($files2);
?>

The above example will output something similar to:

Array
(
    [0] => .
    [1] => ..
    [2] => bar.php
    [3] => foo.txt
    [4] => somedir
)
Array
(
    [0] => somedir
    [1] => foo.txt
    [2] => bar.php
    [3] => ..
    [4] => .
)

Example 2. PHP 4 alternatives to scandir()

<?php
$dir
= "/tmp";
$dh  = opendir($dir);
while (
false !== ($filename = readdir($dh))) {
    
$files[] = $filename;
}

sort($files);

print_r($files);

rsort($files);

print_r($files);

?>

The above example will output something similar to:

Array
(
    [0] => .
    [1] => ..
    [2] => bar.php
    [3] => foo.txt
    [4] => somedir
)
Array
(
    [0] => somedir
    [1] => foo.txt
    [2] => bar.php
    [3] => ..
    [4] => .
)

Tip: You can use a URL as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename and Appendix L for a list of supported URL protocols.

See also opendir(), readdir(), glob(), is_dir(), and sort().