Programming PHP How to read all files and directories in a folder | PHP glob()

How to read all files and directories in a folder | PHP glob()

How to read all files in a folder | PHP glob | Techbriefers

To read all the files in a particular directory using PHP, we can use glob() function. This function allows to read any (pathname) file/ sub directory/ both in a particular directory (in which files are being searched).

Definition:

The glob() function returns an array of filenames or directories matching a specified pattern(given pattern as first argument). The glob() function returns an array containing the matched files/directories names, an empty array if no file/directory is matched and FALSE if any error occurs.

Syntax of glob() function (as on official website)

Description

glob() function uses two parameters. First is mandatory string pattern and second is optional integer (flag).

How to use glob() function

First parameter is a string which is treated as pattern to search pathnames (files/directories).

Using above two folders for search

Examples of glob() function by patterns

Eg-1: To search any file or directory

Eg-2: To search only PHP files

Eg-3: To search only text files

Eg-4: To search any file or directory starts with ‘a’

Eg-4: To search any file or directory starts with ‘tech’

Eg-5: To search any file or directory contains ‘brie’

Eg-6: To search any file or directory that starts with ‘tech’ and end with ‘folder’

Second parameter is an integer which should be a valid flag.

Valid flags:

GLOB_MARK – Adds a slash to the end each directory name found

GLOB_NOSORT – Return files as they appear in the directory without sorting alphabetically. When this flag is not used, the pathnames are sorted alphabetically

GLOB_NOCHECK – Return the search pattern if no files matching it were found

GLOB_NOESCAPE – Backslashes do not quote metacharacters

GLOB_BRACE – Expands {a,b,c} to match ‘a’, ‘b’, or ‘c’

GLOB_ONLYDIR – Return only directory entries which match the pattern

GLOB_ERR – Stop on read errors (like unreadable directories), by default errors are ignored.

Examples of glob() function by flags

Eg-7: To add slash at the end of directory

Eg-8: To see unsorted list of files and directories

Eg-9: If file/folder is not found returns pattern, without using GLOB_NOCHECK returns an empty array

Clear difference can bee seen if you compare Eg-9 and Eg-4. In Eg-4 results are not found hence empty array is returned.

Eg-10: To search only directories (other files are ignored in search)

Searching/ pathnames (files and folders in a paricular sub folder)

Eg-11: To search files and folders in ‘techbriefers-folder’ directory

***I have used echo ‘<pre>’; before printing array to show in a user friendly view.

One thought on “How to read all files and directories in a folder | PHP glob()

Average 
 5 Based On 1

Leave a Reply