Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all .php files in folder recursively

Tags:

php

Using PHP, how can I find all .php files in a folder or its subfolders (of any depth)?

like image 825
Bob Avatar asked Feb 24 '13 18:02

Bob


People also ask

How do I get a list of files in a directory 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.

How do I list all files in a directory recursively?

Linux recursive directory listing using ls -R command. The -R option passed to the ls command to list subdirectories recursively.

How do I recursively search a folder?

An easy way to do this is to use find | egrep string . If there are too many hits, then use the -type d flag for find. Run the command at the start of the directory tree you want to search, or you will have to supply the directory as an argument to find as well. Another way to do this is to use ls -laR | egrep ^d .

What is recursive directory iterator?

The RecursiveDirectoryIterator provides an interface for iterating recursively over filesystem directories.


2 Answers

You can use RecursiveDirectoryIterator and RecursiveIteratorIterator:

$di = new RecursiveDirectoryIterator(__DIR__,RecursiveDirectoryIterator::SKIP_DOTS);
$it = new RecursiveIteratorIterator($di);

foreach($it as $file) {
    if (pathinfo($file, PATHINFO_EXTENSION) == "php") {
        echo $file, PHP_EOL;
    }
}
like image 62
Baba Avatar answered Sep 22 '22 14:09

Baba


just add something like:

function listFolderFiles($dir){
    $ffs = scandir($dir);
    $i = 0;
    $list = array();
    foreach ( $ffs as $ff ){
        if ( $ff != '.' && $ff != '..' ){
            if ( strlen($ff)>=5 ) {
                if ( substr($ff, -4) == '.php' ) {
                    $list[] = $ff;
                    //echo dirname($ff) . $ff . "<br/>";
                    echo $dir.'/'.$ff.'<br/>';
                }    
            }       
            if( is_dir($dir.'/'.$ff) ) 
                    listFolderFiles($dir.'/'.$ff);
        }
    }
    return $list;
}

$files = array();
$files = listFolderFiles(dirname(__FILE__));
like image 24
supajason Avatar answered Sep 22 '22 14:09

supajason