The opendir Function
The opendir
function opens the specified directory and returns its handle (a resource), which is then used with functions for reading the directory contents. After finishing work with the directory, it must be closed using closedir
.
Syntax
opendir(string $path, resource $context = null): resource|false
Example
Basic usage of opendir
:
<?php
$dir = opendir('/path/to/directory');
if ($dir) {
while (($file = readdir($dir)) !== false) {
echo $file . "\n";
}
closedir($dir);
}
?>
Code execution result (example output):
"."
".."
"file1.txt"
"subdirectory"
Example
Handling a directory opening error:
<?php
$dir = opendir('/nonexistent/path');
if ($dir === false) {
echo "Failed to open directory";
} else {
// Work with the directory
closedir($dir);
}
?>
Code execution result:
"Failed to open directory"
Example
Usage with a stream context:
<?php
$context = stream_context_create();
$dir = opendir('ftp://user:password@example.com/', $context);
if ($dir) {
// Read contents of the FTP directory
closedir($dir);
}
?>
This example opens a connection to an FTP server to read the contents of a remote directory.