304 of 410 menu

The closedir Function

The closedir function closes a directory handle that was previously opened by the opendir function. This frees the system resources associated with the handle.

Syntax

closedir(resource $dir_handle): void

Example

Basic usage with opendir:

<?php $dir = opendir('/path/to/directory'); if ($dir) { // Working with the directory closedir($dir); // Closing the handle } ?>

Always close the handle after finishing work with the directory.

Example

Usage in a try-finally block:

<?php $dir = opendir('/path/to/directory'); try { // Working with the directory } finally { if (is_resource($dir)) { closedir($dir); } } ?>

This approach guarantees that the handle will be closed even if an exception occurs.

Example

Closing a handle after scandir:

<?php $dir = opendir('.'); $files = scandir($dir); closedir($dir); print_r($files); ?>

See Also

  • the opendir function,
    which opens a directory handle
  • the readdir function,
    which reads directory contents
  • the scandir function,
    which returns a list of files in a directory
byenru