PHP dir() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
Directory

Definition

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);
CallWhat 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.

Library declarations
PHP
dir(string $directory, ?resource $context = null): Directory|false

Parameters

ParameterDescription
directoryRequired. The path of the folder to open.
contextOptional. A stream context created with stream_context_create(). Most scripts leave it out, and the default is null.

Return Value

Return ValueDescription
Directory|falseReturns 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().

PHP
<?php
$folder = __DIR__ . '/demo-dir';
mkdir($folder);
file_put_contents($folder . '/notes.txt', 'a');
file_put_contents($folder . '/todo.txt', 'b');

$d = dir($folder);
echo "Folder: ", basename($d->path), PHP_EOL;

$names = [];
while (($entry = $d->read()) !== false) {
    if ($entry !== '.' && $entry !== '..') {
        $names[] = $entry;
    }
}
$d->close();

sort($names);
echo "Files: ", implode(', ', $names), PHP_EOL;

unlink($folder . '/notes.txt');
unlink($folder . '/todo.txt');
rmdir($folder);

How It Works

  1. dir($folder) returns a Directory object, and its path property holds the folder we opened.
  2. $d->read() gives one entry per call, and we stop only when it returns false (checked with !==).
  3. We skip '. ' and '..' and then sort the names, because the order from the file system is not guaranteed.
  4. $d->close() releases the folder, and the demo then removes its files and folder.

Example 2 — When the Folder Cannot Be Opened

dir() gives you false instead of an object when something goes wrong. Always check before calling a method.

PHP
<?php
$missing = __DIR__ . '/no-such-folder';

echo "Is it a folder? ", is_dir($missing) ? 'yes' : 'no', PHP_EOL;

$d = @dir($missing);
var_dump($d);

if ($d === false) {
    echo "Could not open the folder.", PHP_EOL;
}

How It Works

  1. is_dir() lets us test for the folder first, which is the cleanest way to avoid a warning.
  2. dir() is still called on the missing path, with @ to hide the warning in this demo.
  3. var_dump() shows the result is bool(false), not an object.
  4. Calling $d->read() on false would crash the script, so we check $d === false first.

Example 3 — Rewinding and Inspecting the Object

The Directory object keeps a handle inside it. We read the folder twice by using rewind(), and we check the handle before and after closing.

PHP
<?php
$folder = __DIR__ . '/demo-dir-rewind';
mkdir($folder);
file_put_contents($folder . '/one.txt', '1');
file_put_contents($folder . '/two.txt', '2');

$d = dir($folder);
echo "Class: ", get_class($d), PHP_EOL;
echo "Handle before close: ", gettype($d->handle), PHP_EOL;

$count = 0;
while (($entry = $d->read()) !== false) {
    if ($entry !== '.' && $entry !== '..') {
        $count++;
    }
}
echo "First pass: ", $count, PHP_EOL;

$d->rewind();
$count = 0;
while (($entry = $d->read()) !== false) {
    if ($entry !== '.' && $entry !== '..') {
        $count++;
    }
}
echo "Second pass: ", $count, PHP_EOL;

$d->close();
echo "Handle after close: ", gettype($d->handle), PHP_EOL;

unlink($folder . '/one.txt');
unlink($folder . '/two.txt');
rmdir($folder);

How It Works

  1. get_class($d) confirms that dir() gives us an object of the built-in Directory class.
  2. The handle property is a normal directory resource, so gettype() reports 'resource'.
  3. After the first loop reaches the end, $d->rewind() moves back to the start so the second loop sees both files again.
  4. $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.

Next: getcwd()

getcwd() returns the current working directory of your script as a string. It answers the .

getcwd() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful