Home »
PHP
PHP opendir() function with example
PHP opendir() function: Here, we are going to learn about the PHP opendir() function with its syntax, parameters, returns type, and example.
Submitted by IncludeHelp, on August 13, 2019
PHP opendir() function
The full form of opendir is "Open Directory", the function opendir() is used to open a directory.
Syntax:
opendir(path,context);
Parameter(s):
- path – It is the path (name) to the directory to be opened.
- context – It is an optional parameter; it defines the context (a set of the options that can modify the behavior of the stream) of the directory handle.
Return value:
If function execution is success – it returns the directory handle resource if function execution is failed – it returns the "FALSE".
Example: PHP code to open a directory, read its files, and close it
<?php
$path = "/home";
//checking whether $path is a directory or not
//then, opening the directory and reading its files
if (is_dir($path)){
if ($dh = opendir($path)){
while (($file = readdir($dh)) !== false){
echo "File:" . $file . "<br/>";
}
//closing the directory
closedir($dh);
}
}
?>
Output
File:..
File:main.php
File:.
Reference: PHP opendir() function
TOP Interview Coding Problems/Challenges