php

How to Use the closedir() Function in PHP

PHP provides various functions to work with directories effectively and efficiently. These functions allow you to perform tasks such as creating and deleting directories, listing directory contents, navigating directory structures, and more. The closedir() function is the built-in function of PHP that is used to close the directory that is previously handled using the opendir() function. The closedir() function is essential for efficient resource management in your PHP scripts.

This guide is about the syntax and usage of the closedir() function of PHP.

PHP closedir() Function

In PHP, you can open any directory using the opendir() function and when you are done with working in that directory, you can close it using the closedir() function.

Syntax

The syntax of using the closedir() function in PHP is as follows:

closedir(dir_handle)

The closedir() function accepts only one parameter, dir_handle, which is optional that specifies the name or path of the directory handle that is in use.

Example 1

The following code will open the directory folder using the opendir() function and then read the content of the directory. The file names within the directory are displayed on the browser using the readdir() function. We then used the closedir() function to close the opened directory:

<?php
$dir = "folder";
// Open a directory, and read its contents
if (is_dir($dir)){
  if ($dh = opendir($dir)){
   while (($file = readdir($dh)) !== false){
        if (is_file($dir . '/' . $file))
    echo "Filename: " . $file . "<br>";
   }
   closedir($dh);
  }
}
?>

Example 2

Here is another example to illustrate the usage of the closedir() function of PHP. The printed directory might contain the dot “.”, which represents the current directory, and double dots “..”, which represents the parent directory.

<?php

  $dir = opendir("files");

  while (($file = readdir($dir)) !== false) {

     echo "filename: " . $file . "<br />";

  }

closedir($dir);

?>

If you want to exclude single and double dots from the output, you can add a simple condition inside the while loop to skip them, below is an updated version of your script:

<?php

$dir = opendir("files");

while (($file = readdir($dir)) !== false) {

  if ($file != '.' && $file != '..') {

     echo "Filename: " . $file . "<br />";

  }

}

closedir($dir);

?>

Bottom Line

The closedir() function in PHP is used to close the opened directory. In PHP, you typically opened a directory using the opendir() function and read the content of the directory using PHP’s readdir() function. It is important to close the previously opened directory to maintain good programming practices and free the system resources.

About the author

Zainab Rehman

I'm an author by profession. My interest in the internet world motivates me to write for Linux Hint and I'm here to share my knowledge with others.