PHP | closedir( ) Function

The closedir() function in PHP is an inbuilt function which is used to close a directory handle. The directory handle to be closed is sent as a parameter to the closedir() function and the closedir() closes the directory handle. The directory handle must be previously opened by the opendir() function.

Syntax:

closedir($dir_handle)

Parameters Used: The closedir() function in PHP accepts only one parameter as described below.



  • $dir_handle: It is an optional parameter which specifies the directory handle resource previously opened with opendir().If this parameter is not specified, the last link opened by opendir() is assumed and closed by closedir().

Return Value: It does not return any value.

Errors And Exceptions:

  1. The directory handle sent as a parameter to the closedir() function must be previously opened by the opendir() function.
  2. If the dir_handle parameter is not specified, the last link opened by opendir() is assumed and closed by closedir() function.

Below programs illustrate the closedir() 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.closedir.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.