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.
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) . "\n";
}
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 .
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.