Several methods for php to traverse directories and folders

Source: Internet
Author: User
Tags foreach explode glob learn php zip

Traverse the directory or traverse the specified type of files under the Directory, which is inevitable for every child shoes when writing programs. PHP itself also provides a lot of gray-often useful functions to use them correctly.
The following is a summary of my personal learning process, hoping to help students who want to learn PHP.

// This function can list all files in a specified directory (including files in subdirectories)

The code is as follows: Copy code

Function getfiles ($ path ){
Foreach (scandir ($ path) as $ afile)
{

If ($ afile = '.' | $ afile = '..') continue;
If (is_dir ($ path. '/'. $ afile ))
{
Getfiles ($ path. '/'. $ afile );
} Else {
Echo $ path. '/'. $ afile. '<br/> ';
}
}
} // Simple demo to list all files in the current directory

Getfiles (_ DIR __);

Scandir () is an array composed of all the files and directories in the specified directory. In PHP, it also provides a very powerful function glob (), glob () there are two parameters. The 2nd parameters are optional. Let's talk about them later. Let's look at how to traverse the directory with glob.

//
// You can see that '.' and '..' are filtered out in the returned content of glob (). * indicates traversing all files in the directory. If it is changed to *. txt, the txt files under the directory will be traversed. Is it convenient? It is more convenient than that. According to Yuan Fang, there is still a big secret in it. What is it? If you are interested, you can leave a message for me.

The code is as follows: Copy code

Function getfiles ($ path ){
Foreach (glob ($ path) as $ afile ){
If (is_dir ($ afile ))
{Getfiles ($ afile. '/*');} else {echo $ afile. '<br/> ';}
}
} // Simple demo to list all files in the current directory
Getfiles (_ DIR _); 0

If *. txt is used, the txt files under the directory will be traversed. What if I want it to traverse files in several formats at the same time? What should I do? Some children's shoes must have thought of using arrays, and then quickly written them and replaced them {*. txt ,*. jpg ,*. zip ,...}, of course, it is also very soon discovered that the program returns false and nothing can be obtained. Don't be disappointed. This involves the 2nd optional parameters just mentioned. This parameter is used to change glob's behavior. For details, refer to the PHP Manual, only one GLOB_BRACE is used to expand {a, B, c ,...} to match 'A', 'B', or 'C ',.... Usage: foreach (glob ($ path. '/{*. txt ,*. jpg ,*. zip ,...} ', GLOB_BRACE) as $ fileName ){...}

For the complete traversal of all the specified file type functions in the directory, we can refer to the following example:


Traverse all files in folders and subfolders

The code is as follows: Copy code


<Html>
<Body>
<? Php
Function traverse ($ path = '.'){
$ Current_dir = opendir ($ path); // opendir () returns a directory handle. If it fails, false is returned.
While ($ file = readdir ($ current_dir ))! = False) {// readdir () returns an entry in the directory handle
$ Sub_dir = $ path. DIRECTORY_SEPARATOR. $ file; // Build the subdirectory path
If ($ file = '.' | $ file = '..'){
Continue;
} Else if (is_dir ($ sub_dir) {// if it is a directory, perform recursion
Echo 'directory '. $ file.': <br> ';
Traverse ($ sub_dir );
} Else {// if it is a file, direct output
Echo 'File in Directory '. $ path.': '. $ File.' <br> ';
                    }
                }
            }
           
Traverse ('xxtt ');
?>
</Body>
</Html>

Some common instances

The code is as follows: Copy code

<? Php
$ Dir = "E:/video"; // enter another path
// PHP traverses all files in the folder
$ Handle = opendir ($ dir .".");
Echo "File: <br> ";
While (false! ==( $ File = readdir ($ handle )))
{
If ($ file! = "." & $ File! = ".."){
Echo $ file; // output file name
}
}
Closedir ($ handle );
?>

I used this code to traverse all files and help me save all file names as an array.

The code is as follows: Copy code

<? Php
$ S = explode ("/n", trim ('DIR/B e: // video '));
Print_r ($ s );
?>

<? Php
$ Dir = "E:/video"; // enter another path
// PHP traverses all files in the folder
$ Handle = opendir ($ dir .".");
Echo "File: <br> ";
While (false! ==( $ File = readdir ($ handle )))
{
If ($ file! = "." & $ File! = ".."){
$ File = $ file. ','; // output file name
$ File = explode (',', $ file );
}
}
Print_r ($ file); // The output is an array.
Closedir ($ handle );
?>

<? Php
$ Dir = "."; // enter another path
// PHP traverses all files in the folder
$ Handle = opendir ($ dir .".");
Echo "File: <br> ";
// Define an array used to store file names
$ Array_file = array ();
While (false! ==( $ File = readdir ($ handle )))
{
If ($ file! = "." & $ File! = ".."){
$ Array_file [] = $ file; // output file name
}
}
Closedir ($ handle );

Print_r ("<pre> ");
Print_r ($ array_file );
Print_r ("</pre> ");
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.