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