I am working on a rather large PHP class that does a lot of things with Image Optimization from the command line, you basically pass the Image path or Folder path program, which has several images inside it. He then runs the files through up to 5 other command line programs that optimize the images.
Below is the part of a loop that collects image paths, if the path is a folder instead of the image path, it will iterate over all the images in the folder and add them to the image array.
So far, everything works for me for single images and images in 1 folder. I would like to modify this section below so that it can recursively go deeper than 1 folder to get image paths.
Can someone show me how I can change this below to accomplish this?
// Get files if (is_dir($path)) { echo 'the path is a directory, grab images in this directory'; $handle = opendir($path); // FIXME : need to run recursively while(FALSE !== ($file = readdir($handle))) { if(is_dir($path.self::DS.$file)) { continue; } if( ! self::is_image($path.self::DS.$file)) { continue; } $files[] = $path.self::DS.$file; } closedir($handle); }else{ echo 'the path is an Image and NOT a directory'; if(self::is_image($path)) { echo 'assign image Paths to our image array to process = '. $path. '<br><br>'; $files[] = $path; } } if (!count($files)) { throw new NoImageFoundException("Image not found : $path"); }
UPDATE
@ Chris's answer made me take a look at Documents, and I found an example that I modified to make it work
public static function find_recursive_images($path) { $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST); foreach ($iterator as $path) { if ($path->isDir()) {
...
$files = self::find_recursive_images($path); echo '<pre>'; print_r($files); echo '</pre>'; exit();
The result is ONLY file names and such a path, which is my final goal, while it works perfectly, but, as always, if there is a better way, Iām all for improvement
( [0] => E:\Server\_ImageOptimize\img\testfiles\css3-generator.png [1] => E:\Server\_ImageOptimize\img\testfiles\css3-please.png [2] => E:\Server\_ImageOptimize\img\testfiles\css3-tools-10.png [3] => E:\Server\_ImageOptimize\img\testfiles\fb.jpg [4] => E:\Server\_ImageOptimize\img\testfiles\mysql.gif [5] => E:\Server\_ImageOptimize\img\testfiles\OriginalImages\css3-generator.png [6] => E:\Server\_ImageOptimize\img\testfiles\OriginalImages\css3-please.png [7] => E:\Server\_ImageOptimize\img\testfiles\OriginalImages\css3-tools-10.png [8] => E:\Server\_ImageOptimize\img\testfiles\OriginalImages\fb.jpg [9] => E:\Server\_ImageOptimize\img\testfiles\OriginalImages\mysql.gif [10] => E:\Server\_ImageOptimize\img\testfiles\OriginalImages\support-browsers.png [11] => E:\Server\_ImageOptimize\img\testfiles\support-browsers.png )
Jasondavis
source share