PHP dir() Function Returns a Directory Class Instance

The PHP dir() function opens a directory and returns a Directory class instance, accepting a directory path and an optional context resource, with detailed parameter descriptions, return values, and a complete example demonstrating how to read entries and close the handle.

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

The dir() function provides an object‑oriented way to access a directory in PHP. It opens the directory specified by the directory argument and optionally accepts a context resource (available since PHP 5.0.0).

Parameters

directory : The path of the directory to be opened.

context : (optional) A context resource for stream operations.

Return value

On success, returns an instance of the Directory class.

On parameter error, returns NULL.

On other errors, returns FALSE.

Example

<?php
$d = dir("/etc/php5");

echo "Handle: " . $d->handle . "
";
echo "Path: " . $d->path . "
";

while (false !== ($entry = $d->read())) {
    echo $entry . "
";
}

$d->close();
?>

Output

Handle: Resource id #2
Path: /etc/php5
.
..
apache
cgi
cli

This example demonstrates creating a Directory object for /etc/php5, printing its handle and path, iterating over all entries, and finally closing the directory handle.

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.

BackendPHPfile system
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.