PHP opendir Function: Opening Directory Handles

This article explains PHP's opendir function, which opens a directory handle for subsequent closedir, readdir, and rewinddir operations, details its parameters and return values, and provides a complete example script demonstrating how to read directory contents and output file names with their types.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP opendir Function: Opening Directory Handles

The opendir function in PHP opens a directory handle that can be used with closedir(), readdir(), and rewinddir() for directory traversal.

Parameters

path : The directory path to open.

context : Optional context resource.

Return value

On success, it returns a resource representing the directory handle; on failure, it returns FALSE.

Example

<?php
$dir = "/etc/php5/";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
    $dh = opendir($dir);
    while (($file = readdir($dh)) !== false) {
        echo "filename: $file : filetype: " . filetype($dir . $file) . "
";
    }
    closedir($dh);
}
?>

The script checks that the directory exists, opens it with opendir, iterates over each entry using readdir, prints the filename and its type via filetype, and finally closes the handle with closedir.

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.

BackendFilesystemdirectoryopendir
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.