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:

  1. 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.
  2. 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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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.");
  
?>

chevron_right


Output:

Directory Opened Successfully.

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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.");
}
?>

chevron_right


Output:

File Name: sample.docx

Reference: http://php.net/manual/en/function.opendir.php



My Personal Notes arrow_drop_up

I am a technology enthusiast who has a keen interest in programming I am pursuing Engineering in Computer Science from GEU, Dehradun I like to unwind by watching movies and English sitcomsI have a keen interest in music

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.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.