Get Contents of Directory in PHP

Retrieve the contents of a directory on the server and put the filenames in an array. There are several methods for retrieving the contents of a directory.

Method 1: The filenames "." and ".." are references to the current directory and the parent directory respectively. You can list any other files which should not be included in the array in the $donotlist array.

$donotlist = array('..', '.', 'index.html', 'index.php', 'index.css', 'index.js', 'blank.html', 'images');
$directorycontents = array_values(array_diff(scandir('.'), $donotlist));

Example:

php array which lists files not to include:
$donotlist = array('..', '.', 'index.html', 'index.php', 'index.css', 'index.js', 'blank.html', 'images');

PHP:
$directorycontents = array_values(array_diff(scandir('.'), $donotlist));

Result:
$directorycontents contains an array of all files in the current directory excluding those listed in $donotlist.


Method 2: Using glob() it isn't necessary to exclude "." and ".."; additionally glob() allows pattern matching. In the example below the pattern is "*.html", so all html files are included. Additional excluding of files can be done using the $donnotlist array.

$donotlist = array('index.html', 'index.php', 'index.css', 'index.js', 'blank.html', 'images');
$directorycontents = array_values(array_diff(glob("*.html"), $donotlist))

Example:

php array which lists files not to include:
$donotlist = array('index.html', 'index.php', 'index.css', 'index.js', 'blank.html', 'images');

PHP:
$directorycontents = array_values(array_diff(glob("*.html"), $donotlist))

Result:
$directorycontents contains an array of all files in the current directory excluding those listed in $donotlist.


$myDirectory = opendir(".");
while($entryName = readdir($myDirectory)) {
    if (contains($entryName,".csv")) {
        $dirArray[] = $entryName;
    }
}
closedir($myDirectory);

Method 3: readdir() lists "." and ".." as current directory and parent directory, which shouldn't be added to the array of filenames in the directory.

$myDirectory = opendir(".");
while($entryName = readdir($myDirectory)) {
    if (strpos($entryName,'.html') !== false) {
        $directorycontents [] = $entryName;
    }
}
closedir($myDirectory);

Example:

PHP:
$myDirectory = opendir(".");
while($entryName = readdir($myDirectory)) {
    if (strpos($entryName,'.html') !== false) {
        $directorycontents [] = $entryName;
    }
}
closedir($myDirectory);

If files need to be excluded they should be specifically listed in the condition in the while loop.

Result:
$directorycontents contains an array of all files in the current directory.