Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the hierarchy of a directory with PHP

I'm trying to find all the files and folders under a specified directory

For example I have /home/user/stuff

I want to return

/home/user/stuff/folder1/image1.jpg
/home/user/stuff/folder1/image2.jpg
/home/user/stuff/folder2/subfolder1/image1.jpg
/home/user/stuff/image1.jpg

Hopefully that makes sense!

like image 678
Callum Avatar asked Mar 19 '09 00:03

Callum


People also ask

What is __ DIR __ in PHP?

The __DIR__ can be used to obtain the current code working directory. It has been introduced in PHP beginning from version 5.3. It is similar to using dirname(__FILE__). Usually, it is used to include other files that is present in an included file.

How do I view a directory in PHP?

PHP scandir() Function$b = scandir($dir,1);

How can I get a list of all the subfolders and files present in a directory using PHP?

PHP using scandir() to find folders in a directory To check if a folder or a file is in use, the function is_dir() or is_file() can be used. The scandir function is an inbuilt function that returns an array of files and directories of a specific directory.

How can I get directory file in PHP?

you can esay and simply get list of file in folder in php. The scandir() function in PHP is an inbuilt function which 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.


2 Answers

function dir_contents_recursive($dir) {
    // open handler for the directory
    $iter = new DirectoryIterator($dir);

    foreach( $iter as $item ) {
        // make sure you don't try to access the current dir or the parent
        if ($item != '.' && $item != '..') {
            if( $item->isDir() ) {
                // call the function on the folder
                dir_contents_recursive("$dir/$item");
            } else {
                // print files
                echo $dir . "/" .$item->getFilename() . "<br>";
            }
        }
    }
}
like image 168
Steve Willard Avatar answered Sep 23 '22 06:09

Steve Willard


foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $f) {
    echo "$f \r\n";   
}
like image 21
Tom Haigh Avatar answered Sep 21 '22 06:09

Tom Haigh