glob()
What is the glob() Function?
The glob() function is a built-in PHP function that searches for files in a directory using a pattern. This function returns an array of file names or directory names that match the specified pattern.
Here's the basic syntax of the glob() function:
The PHP syntax of glob()
glob(pattern, flags);Where pattern is the search pattern and flags is an optional parameter that specifies additional options for the search.
How to Use the glob() Function?
Using the glob() function is straightforward. Here are the steps to follow:
- Specify the search pattern using wildcards or other patterns.
- Call the
glob()function, passing in the search pattern and any optional flags (e.g.,GLOB_NOSORTto disable sorting, orGLOB_BRACEto match multiple patterns). - Use the resulting array to access the files or directories that match the pattern.
Here's an example code snippet that demonstrates how to use the glob() function:
<?php
$files = glob('*.txt');
if ($files !== false) {
foreach ($files as $file) {
echo $file . PHP_EOL;
}
}In this example, we use the glob() function to search for all files with a .txt extension in the current directory. We then use a foreach loop to iterate over the resulting array and print out the names of the files. Note that glob() returns false on error, so it's best practice to check the return value before iterating. For cross-platform compatibility, use forward slashes (/) in your patterns or DIRECTORY_SEPARATOR when building paths dynamically.
Conclusion
The glob() function is a useful tool in PHP for searching for files in a directory using a pattern. By following the steps outlined in this guide, you can easily use the glob() function in your PHP projects to search for files.
Practice
What is the function of the glob() function in PHP?