In PHP, dir() opens a folder and returns a Directory object. It is a pseudo object-oriented way to read a folder, instead of using opendir(), readdir() and closedir() separately.
The Directory object has two properties, path and handle, and three methods: read(), rewind() and close(). They work like readdir(), rewinddir() and closedir(). If the folder cannot be opened, dir() returns false.
Syntax
Call dir() with the values you need. Start with this line.
PHP
$d = dir($folder);
Call
What it does
$d = dir($folder)
Opens the folder and returns a Directory object, or false on failure.
$d->read()
Returns the next entry name, or false when there are no more entries.
$d->close()
Closes the folder when you are finished with it.
Use !== false when looping with $d->read(), for the same reason as readdir(): a file named 0 is a valid entry, but 0 can be mistaken for false in a loose comparison.
Optional. A stream context created with stream_context_create(). Most scripts leave it out, and the default is null.
Return Value
Return Value
Description
Directory|false
Returns a Directory object on success. The object has the properties path and handle, and the methods read(), rewind() and close(). Returns false if the folder cannot be opened.
PHP Examples
Example 1 — Reading a Folder with the Directory Object
We create a demo folder with two files and read it using the object style: $d->read() and $d->close().
Class: Directory
Handle before close: resource
First pass: 2
Second pass: 2
Handle after close: resource (closed)
How It Works
get_class($d) confirms that dir() gives us an object of the built-in Directory class.
The handle property is a normal directory resource, so gettype() reports 'resource'.
After the first loop reaches the end, $d->rewind() moves back to the start so the second loop sees both files again.
$d->close() closes the handle, and the property now reports 'resource (closed)'.
Frequently Asked Questions
It opens a folder and returns a Directory object. You then call read(), rewind() and close() on that object to work with the folder.
They do almost the same job. opendir() gives you a plain resource that you pass to readdir(), rewinddir() and closedir(). dir() wraps the same handle in an object, so you use methods like $d->read().
It returns false and raises a warning, for example when the folder does not exist. Check the result before calling methods on it.
path holds the folder path you passed in, and handle holds the underlying directory resource that opendir() would have returned.
Yes. They are real entries in every folder. Skip them in your loop if you only want real files and folders, and compare the result with !== false.