Method 1: Use dir () to traverse the Directory
Dir () function. If the call succeeds, the Directory class instance is returned.
PHP dir () syntax format:
Dir (directory); // directory is the name of the directory to display the file name, which can contain path information
PHP dir () Usage example: list all file names under the upload Directory:
The code is as follows: |
Copy code |
<? Php $ Dir = @ dir ("upload"); // open the upload directory; "@" can block error messages, because sometimes there is no file in the directory of the file to be displayed, at this time, an error may be reported. Use "@" to hide the error. // List all objects in the upload Directory While ($ file = $ dir-> read ())! = False) { Echo "file name:". $ file. "<br/> "; } $ Dir-> close (); ?> |
Output result:
File name :.
File name :..
File name: logo.gif
File name: arrow.gif
File name: bg.gif
Example
The code is as follows: |
Copy code |
Function tree ($ dir) { $ Mydir = dir ($ dir ); While ($ file = $ mydir-> read ()) { If ($ file! = '.' & $ File! = '..') { If (is_dir ("$ dir/$ file ")) { Echo 'directory name: '. $ dir. DIRECTORY_SEPARATOR.' <font color = "red"> '. $ file.' </font> <br/> '; Tree ("$ dir/$ file "); } Else { Echo 'file name: '. $ dir. DIRECTORY_SEPARATOR. $ file.' <br/> '; } } } $ Mydir-> close (); } Tree ('./phpmyadmin '); |
Method 2 use readir () to traverse the Directory
Definition and usage
The readdir () function returns the entries in the directory handle opened by opendir.
If the call succeeds, the function returns a file name; otherwise, false.
Syntax
Readdir (dir_stream)
Example
The code is as follows: |
Copy code |
Header ('content-type: text/html; charset = utf-8 ');
Function listDir ($ dir) { If (is_dir ($ dir )) { If ($ handle = opendir ($ dir )) { While ($ file = readdir ($ handle )) { If ($ file! = '.' & $ File! = '..') { If (is_dir ($ dir. DIRECTORY_SEPARATOR. $ file )) { Echo 'directory name: '. $ dir. DIRECTORY_SEPARATOR.' <font color = "red"> '. $ file.' </font> <br/> '; ListDir ($ dir. DIRECTORY_SEPARATOR. $ file ); } Else { Echo 'file name: '. $ dir. DIRECTORY_SEPARATOR. $ file.' <br/> '; } } } } Closedir ($ handle ); } Else { Echo 'invalid directory! '; } } ListDir ('./phpmyadmin '); |