Using Glob() to to Find Files In PHP


SUBMITTED BY: PYOGI111

DATE: Oct. 30, 2015, 5:48 a.m.

FORMAT: PHP

SIZE: 1.4 kB

HITS: 555

  1. Many PHP functions have long and descriptive
  2. names. However it may be hard to tell what a
  3. function named glob() does unless you are already familiar with that term from elsewhere. Think of it like a more capable version of the scandir() function. It can let you search for files by using patterns. // get all php files
  4. $files = glob('*.php'); print_r($files);
  5. /* output looks like:
  6. Array
  7. (
  8. [0] => phptest.php
  9. [1] => pi.php [2] => post_output.php
  10. [3] => test.php
  11. )
  12. */ You can fetch multiple file types like this: // get all php files AND txt files
  13. $files = glob('*.{php,txt}', GLOB_BRACE); print_r($files);
  14. /* output looks like:
  15. Array
  16. (
  17. [0] => phptest.php
  18. [1] => pi.php [2] => post_output.php
  19. [3] => test.php
  20. [4] => log.txt
  21. [5] => test.txt
  22. )
  23. */ Note that the files can actually be returned with a
  24. path, depending on your query: $files = glob('../images/a*.jpg'); print_r($files);
  25. /* output looks like:
  26. Array
  27. (
  28. [0] => ../images/apple.jpg
  29. [1] => ../images/art.jpg )
  30. */ If you want to get the full path to each file, you can
  31. just call the realpath() function on the returned values: $files = glob('../images/a*.jpg'); // applies the function to each array element
  32. $files = array_map('realpath',$files); print_r($files);
  33. /* output looks like:
  34. Array
  35. (
  36. [0] => C:\wamp\www\images\apple.jpg
  37. [1] => C:\wamp\www\images\art.jpg )
  38. */

comments powered by Disqus