In PHP, opendir() opens a folder and returns a directory handle. You then pass that handle to readdir() to list the entries, and to closedir() when you are finished.
opendir() is the first step of the classic way to read a folder in PHP: open it, loop with readdir(), then close it. It returns false and raises a warning if the folder cannot be opened, so always check the result.
Syntax
Call opendir() with the values you need. Start with this line.
PHP
$handle = opendir($folder);
Call
What it does
opendir($folder)
Opens the folder and returns a handle, or false if it fails.
opendir(__DIR__)
Opens the folder that holds the current script.
opendir('.')
Opens the current working directory.
opendir() only opens the folder. It does not list anything by itself. If you simply want an array of names, scandir() is shorter and easier for beginners.
Optional. A stream context created with stream_context_create(). Most scripts leave it out, and the default is null.
Return Value
Return Value
Description
resource|false
Returns a directory handle on success. Returns false on failure, for example when the path is not a folder or cannot be read, and PHP also raises an E_WARNING.
PHP Examples
Example 1 — Listing the Files in a Folder
We create a demo folder with three files and use opendir(), readdir() and closedir() together to list them.
The demo folder holds one sub-folder called docs and one file called readme. txt.
readdir() returns only the name, so we add the folder path before calling is_dir().
continue skips '. ' and '..' so only real items are listed.
After sorting, each line shows the name and whether it is a folder or a file.
Frequently Asked Questions
It opens a folder for reading and returns a directory handle. You use that handle with readdir() to get the entries and with closedir() to close the folder.
It returns false and raises an E_WARNING. Check with === false, or test with is_dir() first, before using the handle.
It is good practice. PHP closes the handle at the end of the script, but closing it yourself frees the resource earlier and keeps your code tidy.
For small folders, scandir() is simpler because it returns an array. Use opendir() with readdir() when you want to process entries one at a time, for example in very large folders.
They are special entries that mean 'this folder' and 'the parent folder'. Every folder has them, so skip them in your loop if you only want real files and folders.