How to recursively read a directory with all its content
Posted on September 4, 2008, Filled under PHP,
Bookmark it
This is a very useful snippet if you need to see the complete content of a directory (files, folders, subfolders). The function is defined and applied within its own definition each time folders are found. It’s a recursive function which traverses through the subdirectories until it cannot go any farther.
<?php
/*
Source: Bit Repository
URL: http://www.bitrepository.com/
*/
function read_whole_directory($dir)
{
if ($handle = opendir($dir))
{
$array = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if(is_dir($dir.$file))
{
$array[][$file] = read_whole_directory($dir.$file.'/');
}
else
{
$array[] = $file;
}
}
}
closedir($handle);
}
if(is_array($array))
{
return $array;
}
else
{
return false;
}
}
$dir = '/your/path/to/public_html/'; // IMPORTANT: with '/' at the end
$directory = read_whole_directory($dir);
echo "<pre>"; print_r($directory); echo "</pre>";
?>
NOTE: Make sure your directory string has ‘/’ at the end.
Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!
- September 4, 2008
- article by Gabriel C.
- Leave a reply!
Related Posts
How to Remove a (non-empty) Directory using PHPat September 28, 2008 with 1 comment
PHP: Calculate the Size, Number of Files & Folders of a Directoryat September 24, 2008 with 3 comments
Show random image(s) from a directoryat September 21, 2008 with 3 comments
PHP: Some Ways to Scan a Directoryat December 12, 2008 with 4 comments
PHP: Sort Files from Directory & Order them by Filemtime()at October 5, 2008 with 5 comments
