Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find images with certain extensions recursively

I am currently trying to make a script that will find images with *.jpg / *.png extensions in directories and subdirectories.

If some picture with one of these extensions is found, then save it to an array with path, name, size, height and width.

So far I have this piece of code, which will find all files, but I don't know how to get only jpg / png images.

class ImageCheck {

public static function getDirectory( $path = '.', $level = 0 ){ 

    $ignore = array( 'cgi-bin', '.', '..' ); 
    // Directories to ignore when listing output.

    $dh = @opendir( $path ); 
    // Open the directory to the handle $dh 

    while( false !== ( $file = readdir( $dh ) ) ){ 
    // Loop through the directory 

        if( !in_array( $file, $ignore ) ){ 
        // Check that this file is not to be ignored 

            $spaces = str_repeat( ' ', ( $level * 4 ) ); 
            // Just to add spacing to the list, to better 
            // show the directory tree. 

            if( is_dir( "$path/$file" ) ){ 
            // Its a directory, so we need to keep reading down... 

                echo "<strong>$spaces $file</strong><br />"; 
                ImageCheck::getDirectory( "$path/$file", ($level+1) ); 
                // Re-call this same function but on a new directory. 
                // this is what makes function recursive.  

            } else { 

                echo "$spaces $file<br />"; 
                // Just print out the filename 

            } 

        } 

    } 

    closedir( $dh ); 
    // Close the directory handle 

} 
}

I call this function in my template like this

ImageCheck::getDirectory($dir);
like image 887
George Avatar asked Jul 27 '14 12:07

George


1 Answers

Save a lot of headache and just use PHP's built in recursive search with a regex expression:

<?php

$Directory = new RecursiveDirectoryIterator('path/to/project/');
$Iterator = new RecursiveIteratorIterator($Directory);
$Regex = new RegexIterator($Iterator, '/^.+(.jpe?g|.png)$/i', RecursiveRegexIterator::GET_MATCH);

?>

In case you are not familiar with working with objects, here is how to iterate the response:

<?php
foreach($Regex as $name => $Regex){
    echo "$name\n";
}
?>
like image 192
Wobbles Avatar answered Oct 24 '22 08:10

Wobbles