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 . "
";
echo "Path: " . $d->path . "
";
while (false !== ($entry = $d->read())) {
    echo $entry . "
";
}
$d->close();
?>

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

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendFilesystemexampledirdirectory
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

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.