php – How to get directories recursively?


How do I recursively get all *.php files? With the code below I get all that are root, but I wanted to get all the directories.

I tried using RecursiveDirectoryIterator , or using some functions I found in SOen, like this one , but nothing…

function getPageFiles()
    $directory = '';
    $pages = glob($directory . "*.php");
    //print each file name
    foreach ($pages as $page){
        $row[$page] = $page;
    return $row;


Look, this example shows the files in subdirectories layered within the given scope.


$dir_iterator = new RecursiveDirectoryIterator("../");
    $iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);
    $Regex = new RegexIterator($iterator, '/^.+\.php$/i', RecursiveRegexIterator::GET_MATCH);

    foreach ($Regex as $file) {
        foreach($file as $final){
            echo $final, "<br/>";   


In this case, all .php files that are in the pastas/subpastas of the pointed directory will be displayed.

On the page itself, there are usually examples in the notes at the end of the page. Although this is an example from there, I added a specific line to do what you wanted. I hope it's useful to you.

Scroll to Top