How can the use of opendir() and readdir() functions in PHP lead to errors when handling directories?

When using opendir() and readdir() functions in PHP to handle directories, errors can occur if the directory is not properly closed after use. This can lead to resource leaks and potential memory issues. To avoid this problem, always remember to close the directory handle using closedir() after reading the directory contents.

$dir = opendir('/path/to/directory');

while (($file = readdir($dir)) !== false) {
    // process files
}

closedir($dir);