PHP opendir() Function – Opening a Directory Handle

This article explains PHP's opendir() function, detailing its purpose of opening a directory handle, the required path and optional context parameters, the return values, and provides a complete code example that reads and displays filenames and their types within a specified directory.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP opendir() Function – Opening a Directory Handle

The PHP opendir() function opens a directory handle, returning a resource on success or FALSE on failure.

Parameters

path – the directory path to open.

context – optional context resource.

Return value – a directory handle resource if successful, otherwise FALSE.

Example

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

Output

filename: . : filetype: dir
filename: .. : filetype: dir
filename: apache : filetype: dir
filename: cgi : filetype: dir
filename: cli : filetype: dir
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.

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