A simple way to traverse directories in PHP

Source: Internet
Author: User

There are a lot of functions in PHP that we rarely hear about, but they have very useful functions, such as glob (). Many people want to simply traverse the directory, if you know this function, will be twice the effort.


Glob is included in the kernel from PHP4, not a new function, but like CHECKDNSRR (), few people know about this function. Let's take a look at how to use this function to traverse a directory.
Code



foreach (Glob (' dir/*.php ') as $filename)
{
Echo ' Filename: '. $filename. ' <br/> ';
}






The glob supports two parameters, the second of which is optional. The code above will return all files in the Dir directory with the extension PHP.



Optional parameters

You can use the second argument. Achieve a different purpose. For example, the following code returns two types of files in the Dir directory

$aFiles = Glob (' {dir/*.jpg,mydirectory/*.gif} ', glob_brace);




Glob_brace told GLOB () that I expanded the two different file extensions with curly braces.

PHP defines the following constants, which can be used as the second parameter

Glob_mark-The middle price slash in each returned result
Glob_nosort-Do not sort returned files (in the order they appear)
Glob_nocheck-Returns search mode if no file is found (for example, {dir/*.jpg,mydirectory/*.gif} above)
Glob_noescape-does not turn, that is, the backslash is not used as a conversion character
Glob_brace-Search patterns enclosed in curly braces
Glob_onlydir-returns only the directory names that match the search criteria
Glob_err-Automatic Stop encountered error (default is continue lookup)

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.