-
- $dir = "readdir/";
-
- // Determine whether it is a directory
- if (is_dir($dir)) {
- if ($dh = opendir($dir)) {
- while (($file = readdir($dh)) !== false) {
- echo "filename: $file : filetype: " . filetype($dir . $file) . " ";
- }
- closedir($dh);
- }
- }
Copy the code
Example 2, note that the !== operator does not exist before 4.0.0-RC2.
-
- if ($handle = opendir('/path/to/files')) {
- echo "Directory handle: $handle ";
- echo "Files: ";
-
- /* This is the correct traversal Directory method*/
- while (false !== ($file = readdir($handle))) {
- echo "$file ";
- }
-
- /* This is the wrong way to traverse the directory*/
- while ($ file = readdir($handle)) {
- echo "$file ";
- }
- closedir($handle);
- }
Copy code
Example 3, readdir() will return . and .. entries, Just filter it out if you don't want to use it. Example 2. List all files in the current directory and remove . and....
-
- if ($handle = opendir('.')) {
- while (false !== ($file = readdir($handle))) {
- if ($file != "." && $ file != "..") {
- echo "$file ";
- }
- }
- closedir($handle);
- }
Copy code
Explanation, readdir must be used in conjunction with opendir.
|