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.
// 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>";
}
?>
The script opens the directory, loops through all entries, prints each file name, and finally closes the directory handle to free system resources.
Think of the directory handle as a pointer that moves forward each time readdir() is called, stopping when no more entries are available.
. and .. entries during iteration.