Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP get file listing including sub directories

Tags:

php

glob

I am trying to retrieve all images in a directory, including all subdirectories. I am currently using

$images = glob("{images/portfolio/*.jpg,images/portfolio/*/*.jpg,images/portfolio/*/*/*.jpg,images/portfolio/*/*/*/*.jpg}",GLOB_BRACE); 

This works, however the results are:

images/portfolio/1.jpg images/portfolio/2.jpg images/portfolio/subdirectory1/1.jpg images/portfolio/subdirectory1/2.jpg images/portfolio/subdirectory2/1.jpg images/portfolio/subdirectory2/2.jpg images/portfolio/subdirectory1/subdirectory1/1.jpg images/portfolio/subdirectory1/subdirectory1/2.jpg 

I want it to do a whole directory branch at a time so the results are:

images/portfolio/1.jpg images/portfolio/2.jpg images/portfolio/subdirectory1/1.jpg images/portfolio/subdirectory1/2.jpg images/portfolio/subdirectory1/subdirectory1/1.jpg images/portfolio/subdirectory1/subdirectory1/2.jpg images/portfolio/subdirectory2/1.jpg images/portfolio/subdirectory2/2.jpg 

Greatly appreciate any help, cheers!

P.S It would also be great if I could just get all subdirectories under portfolio without having to specifically state each directory with a wild card.

like image 675
Washburn Avatar asked Aug 24 '12 12:08

Washburn


People also ask

How can I get a list of all the subfolders and files present in a directory using PHP?

PHP using scandir() to find folders in a directory The scandir function is an inbuilt function that returns an array of files and directories of a specific directory. It lists the files and directories present inside the path specified by the user.

How do I list all files in subdirectories?

By default, ls lists just one directory. If you name one or more directories on the command line, ls will list each one. The -R (uppercase R) option lists all subdirectories, recursively.

How do I get a list of files in a directory in PHP?

The scandir() function returns an array of files and directories of the specified directory.

What does Scandir do in PHP?

The scandir() function in PHP is an inbuilt function that is used to return an array of files and directories of the specified directory. The scandir() function lists the files and directories which are present inside a specified path.


1 Answers

from glob example

if ( ! function_exists('glob_recursive')) {     // Does not support flag GLOB_BRACE            function glob_recursive($pattern, $flags = 0)    {      $files = glob($pattern, $flags);      foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir)      {        $files = array_merge($files, glob_recursive($dir.'/'.basename($pattern), $flags));      }      return $files;    } } 
like image 148
diEcho Avatar answered Sep 21 '22 04:09

diEcho