Reputation: 137
i've been looking around SO for an answer, but I quite can't figure out why my code isn't working. I'm trying to grab all picture files from a directory (multiple file extensions, jpg,gif,png,etc) and put it in an array. The problem is with my GLOB code, it only grabs 1 jpg image (the same one every time), despite others being in there.
$imagesDir = 'C:\inetpub\wwwroot\TV\images';
$images = glob($imagesDir . '/*.{jpg,png,gif,jgeg,svg,bmp}', GLOB_BRACE);
$images2 = glob($imagesDir . '/*.*', GLOB_BRACE);
$images3 = glob("C:\inetpub\wwwroot\TV\images.{*jpg,*png,*gif,*bmp,*jpeg,*svg}",
GLOB_BRACE);
I was trying to put the path into the glob command itself, but I couldn't work the syntax.
$images only grabs only a specific jpg file (despite all 7 being jpg though) in the array. $images2 successfully grabs all images in the array (but includes all types of file paths). $images3 straight doesn't work.
My only guess is that the $images only grabs a 1 file and then calls it quits. I was wondering why it wasn't grabbing all of pictures in the directory.
Edit: Putting it in a foreach loop still doesn't work:
foreach (glob($imagesDir . '/*.{jpg,gif,jgeg,svg,bmp}', GLOB_BRACE) as $filename) {
array_push($images, $filename);
}
returns the same image (it is 'always' IMG_8646, despite others jpg images being in there).
Upvotes: 2
Views: 3382
Reputation: 4379
Best to use an interator DirectoryInterator, here's a code snippet:-
$valid_ext = array("jpg", "gif", "jpeg", "svg", "bmp"); // valid extensions
foreach (new DirectoryIterator($imagesDir) as $fileInfo) { // interator
if (in_array($fileInfo->getExtension(), $valid_ext) ) { // in $valid_ext
echo $fileInfo->getFilename() . "<br>\n"; // do something here
}
}
Upvotes: 4
Reputation: 816
You should be using foreach(){}
to iterate though the glob function. as
foreach (glob('/path/to/images/*.jpg') as $filename) {
//echo file name
}
Upvotes: 1