PHP scandir: Read Directory Contents into an Array
This article provides a straightforward guide on how to use the
built-in scandir() function in PHP to read the files and
directories of a specific path into an array. You will learn the basic
syntax, how to handle the default directory pointers (. and
..), how to sort the output, and how to safely implement
this function in your web applications.
Basic Usage of scandir()
The scandir() function in PHP accepts a directory path
as its primary argument and returns an array of files and directories
found inside that path. If the directory does not exist or cannot be
read, it returns false.
Here is the simplest way to use it:
$dir = "./my_directory";
// Read the directory contents into an array
$files = scandir($dir);
// Output the array
print_r($files);Filtering Out Default Directory Pointers
By default, scandir() includes the current directory
(.) and parent directory (..) pointers in the
returned array. To clean up your array and only keep actual files and
folders, you can use array_diff().
$dir = "./my_directory";
// Scan and filter out '.' and '..'
$files = array_diff(scandir($dir), array('.', '..'));
// Re-index the array keys starting from 0
$files = array_values($files);
print_r($files);Sorting the Directory Contents
The scandir() function provides a second argument to
control the sorting order of the returned array. PHP offers three
built-in constants for this purpose:
SCANDIR_SORT_ASCENDING(Default): Sorts alphabetically in ascending order.SCANDIR_SORT_DESCENDING: Sorts alphabetically in descending order.SCANDIR_SORT_NONE: Returns the files in the order they are stored by the filesystem.
$dir = "./my_directory";
// Sort descending
$files_desc = scandir($dir, SCANDIR_SORT_DESCENDING);
// No sorting (faster performance for large directories)
$files_unsorted = scandir($dir, SCANDIR_SORT_NONE);Safe Implementation with Error Handling
To prevent PHP warnings or crashes, always verify that the directory
exists and is readable before running scandir().
$dir = "./my_directory";
if (is_dir($dir)) {
if ($files = scandir($dir)) {
// Filter out parent and current directory pointers
$clean_files = array_diff($files, array('.', '..'));
foreach ($clean_files as $file) {
echo $file . "<br>";
}
} else {
echo "Failed to read directory contents.";
}
} else {
echo "Directory does not exist.";
}