Help with recursive glob()

Hi guys,
Hope you could help me, I found out that I need my code to work recursively, but I have no idea how :confused: been trying for quite long now, so I am hoping you might help me

This is the code I have - it works - but not with the folders under uploads:
[php] <?php

$images = glob('./uploads/*.{gif,png,jpg,jpeg}', GLOB_BRACE); //formats to look for

$num_of_files = 12; //number of images to display

foreach($images as $image)
{
     $num_of_files--;

     if($num_of_files > -1)
       echo "<li class=\"span4\"><a href=\"/foto\" class=\"thumbnails\"><img src="."'".$image."'"." /></a></li>" ; //display images
     else
       break;
}

?>[/php]

Could any of you kindly please rewrite it for me, to accept the folders under ā€œuploadsā€? Thank you very much! :slight_smile:

I personally donā€™t like using glob but if someone wants to help you with that they can :slight_smile:

I would recommend using the built in Iterators: http://php.net/manual/en/spl.iterators.php

Example:

[php]

<?php $path = '/path/to/uploads'; // path to directory to search $extensions = array('gif', 'png', 'jpg', 'jpeg'); // extensions to allow // combining RecursiveIteratorIterator with RecursiveDirectoryIterator // allows you to search all sub-directories $objs = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST); foreach($objs as $obj) { // skip everything that is not a file if (!$obj->isFile()) { continue; } // skip everything that does not match $extensions $extension = pathinfo($obj->getPathname(), PATHINFO_EXTENSION); // get extension if (!in_array($extension, $extensions)) { continue; } // this is a file that matches $extensions echo $obj->getPathname() . PHP_EOL; } ?>

[/php]

Hi m@tt! Thanks for the excellent job, one more thingā€¦is there any chance you could write one more thing into this script for me, or give me a hint on how to make it so that it shows 12 latest files? :slight_smile:

Iā€™ve been able to find some snippets here and there but none of them seems to work correctly :frowning: thanks a lot!

P.S.: If you have paypal, tell me your address, Iā€™d like to buy you a beer or two :slight_smile: thanks:)

That is quite a bit different and I think depends on how many files you are searching. If there are thousands of files you may way to use a shell command, otherwise you could just build an array based on filemtime(), sort it and pull the top 12.

oh yeah :slight_smile: thanks I think Iā€™ll be able to continue from here on my own, thanks again :slight_smile:

Sponsor our Newsletter | Privacy Policy | Terms of Service