Wednesday, November 20, 2024
Google search engine
HomeLanguagesPHP | closedir( ) Function

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:




<?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

RELATED ARTICLES

Most Popular

Recent Comments