← Back to Chapters

PHP opendir(), readdir(), closedir()

? PHP opendir(), readdir(), closedir()

? Overview

PHP provides several functions for interacting with directories, including opendir(), readdir(), and closedir(). These functions allow you to open a directory, read its contents, and then close the directory after you’re done working with it.

?️ Key Concepts

  • opendir() opens a directory and returns a handle.
  • readdir() reads directory entries one by one.
  • closedir() releases the directory resource.

? Syntax & Theory

  • opendir(path) requires read permission on the directory.
  • readdir(handle) returns file or directory names.
  • closedir(handle) should always be called after reading.

? Code Example

? View Code Example
// Open a directory, read files, and close it safely
<?php
$directory_path = "./myFolder";
$dir = opendir($directory_path);

if ($dir) {
echo "Files in '$directory_path':<br>";
while (($file = readdir($dir)) !== false) {
echo $file . "<br>";
}
closedir($dir);
} else {
echo "Failed to open directory.<br>";
}
?>

? Output / Explanation

The script opens the directory, loops through all entries, prints each file name, and finally closes the directory handle to free system resources.

? Interactive Understanding

Think of the directory handle as a pointer that moves forward each time readdir() is called, stopping when no more entries are available.

? Use Cases

  • Listing uploaded files.
  • Processing batch files.
  • Scanning folders for backups or logs.

✅ Tips & Best Practices

  • Always validate directory paths before opening.
  • Skip . and .. entries during iteration.
  • Close directories to prevent memory leaks.

? Try It Yourself

  • Count files in a directory using readdir().
  • Filter files by extension.
  • Test behavior with nested directories.