In PHP, closedir() closes a directory handle that was opened with opendir(). It tells PHP you are finished reading the folder.
When you open a folder with opendir(), PHP keeps a connection to it open. closedir() releases that connection. It is good practice to call it as soon as you are done with readdir(), just like you call fclose() for files. It always returns true.
Syntax
Call closedir() with the values you need. Start with this line.
PHP
closedir($handle);
Call
What it does
closedir($handle)
Closes the directory handle stored in $handle.
$handle = opendir($folder); closedir($handle);
Opens a folder and closes it again right away.
closedir()
Closes the most recently opened handle. This works, but passing the handle is clearer and recommended.
Always pass the handle you got from opendir(). Calling closedir() with no argument relies on the last opened directory, which is confusing and is deprecated in PHP 8.5 and later.
Library declarations
PHP
closedir(?resource $dir_handle = null): true
Parameters
Parameter
Description
dir_handle
Optional. The directory handle returned by opendir(). If it is left out or null, PHP uses the last directory handle that was opened, but you should always pass the handle explicitly.
Return Value
Return Value
Description
true
Always returns true. In older PHP versions this function had no useful return value.
PHP Examples
Example 1 — Opening and Closing a Directory Handle
We open an empty demo folder, check the handle, close it, and check it again to see what closedir() changed.
countFiles() opens the folder, loops through every entry with readdir(), and counts them.
The entries '. ' and '..' are skipped because they are not real files.
closedir($handle) runs before the function returns, so the handle is always released.
The demo creates three files, prints the count, and then removes everything it created.
Frequently Asked Questions
It closes a directory handle that was opened with opendir(). This releases the resource PHP was holding for that folder.
PHP closes open handles when the script ends, so small scripts will not break. Still, it is good practice to call closedir() as soon as you finish reading, especially in long running scripts or loops.
It returns true. Older versions of PHP did not return a useful value, so most code never checks the result.
PHP throws a TypeError because the resource is no longer valid. Open the folder again with opendir() to get a new handle.
Yes, PHP then closes the last opened directory handle. This is deprecated in PHP 8.5 and later, so always pass the handle that opendir() gave you.