PHP | opendir() Function
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:
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.
Return Value: It returns a directory handle resource on success, or FALSE on failure.
Errors And Exceptions:
- 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.
Below programs illustrate the opendir() function:
Program 1:
<?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."); } ?> |
Output:
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."); } ?> |
Output:
File Name: sample.docx
Reference: http://php.net/manual/en/function.opendir.php
Recommended Posts:
- How to call a function that return another function in JavaScript ?
- How to get the function name from within that function using JavaScript ?
- How to get the function name inside a function in PHP ?
- PHP | Ds\Set xor() Function
- D3.js | d3.max() function
- PHP | Ds\Map xor() Function
- PHP | pow( ) Function
- PHP | each() Function
- PHP | Ds\Map put() Function
- PHP | Ds\Set add() Function
- p5.js | hex() function
- PHP | key() Function
- CSS | rgb() Function
- PHP | min( ) Function
- PHP | pos() Function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



