-
- function myscandir($pathname){
- foreach( glob($pathname) as $filename ){
- if(is_dir($filename)){
- myscandir($filename.'/*' );
- }else{
- echo $filename.'
';
- }
- }
- }
- myscandir('D:/wamp/www/exe1/*');
- ?>
Copy the code
2. Method 2
-
- function myscandir($path){
- $mydir=dir($path);
- while($file=$mydir->read()){
- $p=$path .'/'.$file;
- if(($file!=".") AND ($file!="..")){
- echo $p.'
';
- }
- if( (is_dir($p)) AND ($file!=".") AND ($file!="..")){
- myscandir($p);
- }
- }
- }
- myscandir(dirname(dirname( __FILE__)));
- ?>
Copy code
2. Usage of php directory traversal function opendir
The function of opendir() function:
Open the directory handle. If the function runs successfully, it will return a set of directory streams (a set of directory strings). If it fails, it will return an error [error]. You can add "@" at the front of the function to hide the error.
syntax syntax: opendir(directory,context) parameter
Parameter:description
Description: directory required. specifies the directory to stream
Required parameters specify the directory object. Optional parameters specify the context of the directory object that needs to be processed. This context includes a set of options that can change the display mode of the text stream.
Code:
-
- $dir = "./";
-
- // open a known directory, and proceed to read its contents
- if (is_dir($dir))
- {
- if ($dh = opendir($dir)) {
- while (($file = readdir($dh)) !== false) {
- echo "filename: $file : filetype: " . filetype($dir . $file) . "n "."
";
- }
- closedir($dh);
- }
- }
- ?>
PHP does not need to recurse to implement the code to list all files in a directory
Code:
/** * PHP non-recursive implementation to query all files in the directory * @param unknown $dir * @return multitype:|multitype:string*/ function scanfiles($dir) { if (! is_dir ( $dir ))- return array ();
- < ;p> // Compatible with all operating systems
- $dir = rtrim ( str_replace ( '\', '/', $dir ), '/' ) . '/';
// Stack, the default value is the passed in directory
- $dirs = array ( $dir );
// Container to place all files
- $rt = array ();
-
do {
- // Pop the stack
- $dir = array_pop ( $dirs );
// Scan the directory
- $tmp = scandir ( $dir );
foreach ( $tmp as $f ) {
- // Filter. ..
- if ($f == '.' || $f == '..')
- continue;
-
- // Combine the current absolute path
- $path = $dir . $f;
-
- // If it is a directory, push it onto the stack.
- if (is_dir ( $path )) {
- array_push ( $dirs, $path . '/' );
- } else if (is_file ( $path )) { // If it is a file, put it in the container
- $rt [ ] = $path;
- }
- }
} while ( $dirs ); // Until there is no directory in the stack
return $rt;
- }< ;/p>
-
-
- Copy code
-
-
-
-
-
-
|