In PHP, readdir() returns the name of the next entry in an open directory. Each call gives you one name, and it returns false when there are no more entries.
You use readdir() together with opendir() and closedir(). Put it in a while loop to visit every item in a folder. The names come back in the order the file system stores them, which is not alphabetical, and the list includes the special entries '.' and '..'.
Syntax
Call readdir() with the values you need. Start with this line.
PHP
while (($entry = readdir($handle)) !== false) { ... }
Call
What it does
readdir($handle)
Returns the next entry name, such as 'photo.jpg', or false at the end of the folder.
($entry = readdir($handle)) !== false
The safe loop condition. It stops only when readdir() returns false.
readdir()
Reads from the last opened handle. This is deprecated in PHP 8.5 and later, so pass the handle instead.
Always compare with !== false. A file or folder can be named 0, and the string '0' counts as false in a loose check, which would end your loop too early.
Optional. The directory handle returned by opendir(). If it is left out or null, PHP uses the last opened handle. Passing null is deprecated in PHP 8.5 and later, so always pass the handle.
Return Value
Return Value
Description
string|false
Returns the name of the next entry (just the name, not the full path). Returns false when there are no more entries.
PHP Examples
Example 1 — Looping Through a Folder
The standard readdir() loop: read one name at a time until false, skip the dot entries, and sort the result.
The folder holds a single file, so after skipping the dot entries the counter ends at 1.
The loop only ends because readdir() has returned false.
Calling readdir() one more time still returns false, because there is nothing left to read.
To read the folder again from the start, call rewinddir() or open a new handle.
Frequently Asked Questions
It returns the name of the next entry in a directory that was opened with opendir(). Calling it repeatedly walks through the whole folder, and it returns false when the end is reached.
Because an entry can be named 0, and the string '0' is treated as false in a loose comparison. With !== false, the loop only stops at the real end of the folder.
They are special entries present in every folder. '.' means the folder itself and '..' means its parent. Skip them if you only want real files and folders.
No. The order depends on the file system and can change between systems. Collect the names in an array and sort() them, or use scandir(), which sorts for you.
PHP will use the last opened directory, but this is deprecated in PHP 8.5 and later. Always pass the handle returned by opendir().