How can the opendir and readdir functions in PHP be used to iterate through directories and files?

To iterate through directories and files in PHP, you can use the opendir and readdir functions. opendir opens a directory handle, and readdir reads the next entry from the directory handle. By combining these two functions in a loop, you can iterate through all the files and directories within a given directory.

$dir = "/path/to/directory";

if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            if ($file != '.' && $file != '..') {
                echo "File: $file\n";
            }
        }
        closedir($dh);
    }
}