Open In App

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.

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:




<?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.closedir.php


Article Tags :