This article mainly introduces examples of php traversal folders and file lists. For more information, see
This article mainly introduces examples of php traversal folders and file lists. For more information, see
I wrote a simple class for PHP to traverse directories and file lists, and attached the example for your reference.
The Code is as follows:
Define ('ds', DIRECTORY_SEPARATOR );
Class getDirFile {
// Returns an array.
Private $ DirArray = array ();
Private $ FileArray = array ();
Private $ DirFileArray = array ();
Private $ Handle, $ Dir, $ File;
// Obtain the Directory List
Public function getDir (& $ Dir ){
If (is_dir ($ Dir )){
If (false! = ($ Handle = opendir ($ Dir ))){
While (false! = ($ File = readdir ($ Handle ))){
If ($ File! = '.' & $ File! = '..'&&! Strpos ($ File ,'.')){
$ DirArray [] = $ File;
}
}
Closedir ($ Handle );
}
} Else {
$ DirArray [] = '[Path]: \ ''. $ Dir.' \ 'is not a dir or not found! ';
}
Return $ DirArray;
}
// Obtain the file list
Public function getFile (& $ Dir ){
If (is_dir ($ Dir )){
If (false! = ($ Handle = opendir ($ Dir ))){
While (false! = ($ File = readdir ($ Handle ))){
If ($ File! = '.' & $ File! = '..' & Strpos ($ File ,'.')){
$ FileArray [] = $ File;
}
}
Closedir ($ Handle );
}
} Else {
$ FileArray [] = '[Path]: \ ''. $ Dir.' \ 'is not a dir or not found! ';
}
Return $ FileArray;
}
// Obtain the directory/file list
Public function getDirFile (& $ Dir ){
If (is_dir ($ Dir )){
$ DirFileArray ['dirlist'] = $ this-> getDir ($ Dir );
If ($ DirFileArray ){
Foreach ($ DirFileArray ['dirlist'] as $ Handle ){
$ File = $ Dir. DS. $ Handle;
$ DirFileArray ['filelist'] [$ Handle] = $ this-> getFile ($ File );
}
}
} Else {
$ DirFileArray [] = '[Path]: \ ''. $ Dir.' \ 'is not a dir or not found! ';
}
Return $ DirFileArray;
}
}
?>
Instance: (relative or absolute path)
1. Get the Directory List
The Code is as follows:
$ Dir_dir = './example ';
$ GetDirFile = new getDirFile ();
$ GetDir = $ getDirFile-> getDir ($ Dir_dir );
Print_r ($ getDir );
?>
Display
The Code is as follows:
$ File_one_dir = './example/example_one ';
$ File_two_dir = 'e:/Workspace/mycode/getDirFile/example/example_two ';
$ GetDirFile = new getDirFile ();
$ GetFile_one = $ getDirFile-> getFile ($ File_one_dir );
$ GetFile_two = $ getDirFile-> getFile ($ File_two_dir );
Print_r ($ getFile_one );
Print_r ($ getFile_two );
?>
2. Get the file list
The Code is as follows:
$ File_one_dir = './example/example_one ';
$ File_two_dir = 'e:/Workspace/mycode/getDirFile/example/example_two ';
$ GetDirFile = new getDirFile ();
$ GetFile_one = $ getDirFile-> getFile ($ File_one_dir );
$ GetFile_two = $ getDirFile-> getFile ($ File_two_dir );
Print_r ($ getFile_one );
Print_r ($ getFile_two );
?>
Display
The Code is as follows: