Using PHP's scandir() function to find files in a directory

Posted in PHP -

There are a number of ways to find the files in a directory with PHP. I've covered opendir() readdir() and closedir() and glob() in previous posts and now look at scandir().

Example directory

The examples below look at a directory with the following, the same example directory as used in the read through directory and glob posts:

bar.txt       A regular file
baz           A directory
foo.txt       A regular file
link2foo.txt  A symbolic link to foo.txt

Simple example

The following example reads all the files in the directory at /path/to/directory into an array using scandir() and then echos out the array:

$files = scandir("/path/to/directory");
print_r($files);

The output from the above using the example directory is as follows:

Array
(
    [0] => .
    [1] => ..
    [2] => 1.jpg
    [3] => 2.gif
    [4] => 3.png
    [5] => bar.txt
    [6] => baz
    [7] => foo.txt
    [8] => link2foo.txt
)

By default scandir() sorts the files into alphabetical order. To reverse the order pass a non-zero value as the second parameter like so:

$files = scandir("/path/to/directory", 1);
print_r($files);

will the resulting output:

Array
(
    [0] => link2foo.txt
    [1] => foo.txt
    [2] => baz
    [3] => bar.txt
    [4] => 3.png
    [5] => 2.gif
    [6] => 1.jpg
    [7] => ..
    [8] => .
)

Excluding the . and .. directories

To exclude the . and .. directory aliases you can do this:

$files = array_diff( scandir("/path/to/directory"), array(".", "..") );

This saves having to conditionally check for these when looping through the array.



Related posts:


Comments