Php glob get all files in directory

In this beginner’s tutorial, I will show you how to list all files in a directory using PHP. We will do this using PHP’s glob function, which allows us to retrieve a list of file pathnames that match a certain pattern.

For this example, I have created a folder called “test”. Inside the folder, I have created three files:

  • test.txt
  • names.txt
  • file.php

Here is a screenshot of the directory:

Php glob get all files in directory

In our first PHP code snippet, we will simply list everything that is in the test folder:

'; 
}

The result will look something like this:

test/file.php
test/names.txt
test/test.txt

However, what if we wanted to list all files with a particular file extension? i.e. What if we only want to list the .txt files and not the .php file that is currently present?

Well, the solution is pretty simple:

//Get a list of all files ending in .txt
$fileList = glob('test/*.txt');

In the code snippet above, we told the glob function to return a list of file pathnames that ended .txt

Warning: In some cases, the folder may have subdirectories. In cases where you are listing everything that is inside a specified folder, these subdirectories will be returned by the glob function. To avoid printing out or interacting with subdirectories, you can simply use the is_file function to confirm that the file pathname in question leads to an actual file:

'; 
    }   
}

Hopefully, this tutorial was useful!

Related: Delete all files in a folder using PHP.

❮ PHP Filesystem Reference

Example

Return an array of filenames or directories that matches the specified pattern:

print_r(glob("*.txt"));
?>

The output of the code above could be:

Array (
  [0] => target.txt
  [1] => source.txt
  [2] => test.txt
  [3] => test2.txt
)



Definition and Usage

The glob() function returns an array of filenames or directories matching a specified pattern.

Syntax

Parameter Values

ParameterDescription
pattern Required. Specifies the pattern to search for
flags Optional. Specifies special settings.

Possible values:

  • GLOB_MARK - Adds a slash to each item returned
  • GLOB_NOSORT - Return files as they appear in the directory (unsorted)
  • GLOB_NOCHECK - Returns the search pattern if no match 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 directories which match the pattern
  • GLOB_ERR - (added in PHP 5.1) Stop on errors (errors are ignored by default)


Technical Details

Return Value:An array of files/directories that matches the pattern, FALSE on failure
PHP Version:4.3+
PHP Changelog:PHP 5.1: GLOB_ERR value added to the flags parameter

More Examples

Example

Return an array of filenames or directories that matches the specified pattern:

print_r(glob("*.*"));
?>

The output of the code above could be:

Array (
  [0] => contacts.csv
  [1] => default.php
  [2] => target.txt
  [3] => source.txt
  [4] => tem1.tmp
  [5] => test.htm
  [6] => test.ini
  [7] => test.php
  [8] => test.txt
  [9] => test2.txt
)



❮ PHP Filesystem Reference


glob() function is a built-in PHP function that is used to search the specific files or folders based on the pattern. It returns the file and folder names in an array that matches the pattern. How this function can be used to search the particular files or folders is shown in this tutorial.

Syntax:

The syntax of the glob() function is given below. This function can take two arguments. The first argument takes the pattern value that will be used to search the file and folder. The second argument is optional that is used to generate the output in different ways. The common symbols that are used to define the pattern and the different types of flags that can be used in the second argument of this function are described below.

array glob ( string $pattern [, int $flags = 0 ] )

Mostly used symbols in the pattern

PatternPurpose
? It is used to match exactly one character (any).
* It is used to match zero or more characters.
\ It is used to escape the characters when the GLOB_NOESCAPE flag is used.
[…] It is used to match the range of characters.

Flag values

The following flag values can be used in the optional argument of the glob() function.

ValuePurpose
GLOB_MARK It adds a slash with each returned item.
GLOB_NOSORT It returns unsorted files that appear in the directory.
GLOB_NOCHECK It returns the search pattern if no match is found.
GLOB_NOESCAPE It uses backslashes and doesn’t quote metacharacters.
GLOB_BRACE It expands the characters from a group to match.
GLOB_ONLYDIR It returns the directory list that only matched with the pattern.
GLOB_ERR It is used to stop when the error occurs.

Example 1: Read all PHP files using the ‘*’ symbol

The following example shows the way to search all PHP files of the current location using the ‘*.php’ pattern. Create a PHP file with the following script.

The pattern will search any filename with the extension PHP. The return value of the function is an array that will be printed as output.


//Print the list of text files of the current directory
print_r(glob("*.php"));
?>

Output:

The following output will appear after running the script from the server. It shows that five PHP files exist in the current location.

Php glob get all files in directory

Example 2: Read specific text files using the ‘?’ symbol

The following example will search all text files that contain a filename of five characters. Create a PHP file with the following script.

The ‘?????.txt’ pattern is used to search the text file with the five-characters filename. The output of the glob() function is an array that is stored in the variable, $files. The values of this variable are printed by using the foreach loop.


   //Read specific text filenames of the current location
   $files = glob("?????.txt");
     //Print the file names
   foreach ($files as $file) {
      echo "" . $file. "
"
;
   }
?>

Output:

The following output will appear after running the script from the server. It shows that two text files exist in the current location according to the pattern.

Php glob get all files in directory

Example 3: Read all files of the current location using the loop

The following example will search all types of files from the current location and print the filenames in each line by using the loop. ‘*.*’ pattern is used in the glob() function to search any file of any type. The returned value of the function is stored in the array, $files. Then, the total number of files is counted from the searched result. foreach loop is used to print the values of the array in each line.


   //Read all filenames of the current location
   $files = glob("*.*");
   //Count the total number of files
   $count = count($files);
   echo "Total files = $count

"
;
   echo "The files are :
"
;
   //Print the file names
   foreach ($files as $file) {
      echo "" . $file. "
"
;
   }
?>

Output:

The following output will appear after running the script from the server. It shows that six files exist in the current location.

Php glob get all files in directory

Example 4: Search file that starts with the specific character

The following example will search the PHP file that starts with the character ‘g’. Create a PHP file with the following script.

‘g*.php’ is used as the pattern for searching the files. Like the previous examples, the returned value of the glob() function is stored in an array that is printed later using a foreach loop.


    //Search file start with 'g'
    $files = glob("g*.php");
    //Print the files
    foreach ($files as $file) {
         echo $file. "
"
;
   }
?>

Output:

The following output will appear after running the script from the server. It shows that four PHP files exist in the current location where the files start with the character ‘g’.

Php glob get all files in directory

Example 5: Read all files and folders

The pattern used in all previous examples searched only the files from the current location. The following example shows the way to search all files and folders of the current location. Create a PHP file with the following script.

‘*’ is used as a pattern in the glob() function to search all files and folders. The returned values of the function are stored in an array that is printed later.


    //Read all files and folders of the current location
    $files = glob("*");
    //Print the files and folders
    foreach ($files as $file) {
        echo $file. "
"
;
   }
?>

Output:

The following output will appear after running the script from the server. It shows that five PHP files, three text files, and two folders exist in the current location.

Php glob get all files in directory

Conclusion

The methods of searching any file or folder are shown in this tutorial using the glob() function of PHP. The file can be searched based on the extension, the starting character, or by specifying the total number of characters. Hopefully, the use of the glob() function in PHP will be clearer and easier for the readers after practicing the examples of this tutorial.

About the author

Php glob get all files in directory

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.