The readdir Function
The readdir
function reads the contents of a directory opened with opendir
. On each call, it returns the name of the next file or false
if there are no more files. The function maintains an internal position pointer within the directory.
Syntax
readdir(resource $dir_handle): string|false
Example
Reading all files in a directory:
<?php
$dir = opendir('/path/to/directory');
while (($file = readdir($dir)) !== false) {
echo $file . '<br>';
}
closedir($dir);
?>
Code execution result (example output):
"file1.txt"
"file2.jpg"
"subdirectory"
Example
Filtering special entries '.' and '..':
<?php
$dir = opendir('.');
while (($file = readdir($dir)) !== false) {
if ($file != '.' && $file != '..') {
echo $file . '<br>';
}
}
closedir($dir);
?>
Code execution result (outputs only real files and subdirectories):
'index.php'
'styles.css'
'images'
Example
Collecting all files into an array:
<?php
$files = [];
if ($handle = opendir('/path/to/dir')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != '.' && $entry != '..') {
$files[] = $entry;
}
}
closedir($handle);
}
print_r($files);
?>
Code execution result:
Array
(
[0] => "document.pdf"
[1] => "image.png"
[2] => "data.json"
)