Backend Development 2 min read

PHP dir() Function – Returns a Directory Instance

The article explains PHP's dir() function, detailing its parameters, return values, and providing a complete example that demonstrates opening a directory, retrieving its handle and path, iterating over entries, and closing the directory resource.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP dir() Function – Returns a Directory Instance

The dir() function in PHP returns a Directory class instance, allowing object‑oriented access to a filesystem directory specified by the $directory argument.

Parameters:

directory – the path of the directory to open (string).

context – optional stream context resource (available since PHP 5.0.0).

Return value:

On success, a Directory object.

If a parameter error occurs, null .

For other errors, false .

Example usage:

<?php
$d = dir("/etc/php5");
echo "Handle: " . $d->handle . "\n";
echo "Path: " . $d->path . "\n";
while (false !== ($entry = $d->read())) {
    echo $entry . "\n";
}
$d->close();
?>

The script prints the directory handle resource ID and the path, then lists each entry in the directory.

backendExampledirdirectory
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.