PHP | opendir() Function
Last Updated :
11 Jul, 2018
Improve
The opendir() function in PHP is an inbuilt function which is used to open a directory handle. The path of the directory to be opened is sent as a parameter to the opendir() function and it returns a directory handle resource on success, or FALSE on failure.
The opendir() function is used to open up a directory handle to be used in subsequent with other directory functions such as closedir(), readdir(), and rewinddir().
Syntax:
php
Output:
php
Output:
opendir($path, $context)Parameters Used: The opendir() function in PHP accepts two parameters.
- $path : It is a mandatory parameter which specifies the path of the directory to be opened.
- $context : It is an optional parameter which specifies the behavior of the stream.
- A PHP error of level E_WARNING is generated and opendir() returns FALSE if the path is not a valid directory or the directory cannot be opened due to permission restrictions or filesystem errors.
- The error output of opendir() can be suppressed by prepending '@' to the front of the function name.
<?php
// Opening a directory
$dir_handle = opendir("/user/gfg/docs/");
if(is_resource($dir_handle))
{
echo("Directory Opened Successfully.");
}
// closing the directory
closedir($dir_handle);
else
{
echo("Directory Cannot Be Opened.");
}
?>
Directory Opened Successfully.Program 2:
<?php
// opening a directory and reading its contents
$dir_handle = opendir("user/gfg/sample.docx");
if(is_resource($dir_handle))
{
while(($file_name = readdir($dir_handle)) == true)
{
echo("File Name: " . $file_Name);
echo "<br>" ;
}
// closing the directory
closedir($dir_handle);
}
else
{
echo("Directory Cannot Be Opened.");
}
?>
File Name: sample.docxReference: http://php.net/manual/en/function.opendir.php