How to recursively read a directory with all its content

Posted on September 4, 2008, Filled under PHP,  Bookmark it

Thanks for visiting our website! We regularly publish posts like this one. If you are interested in receiving the latest updates as soon as they are posted, please consider subscribing to the RSS feed or to our e-mail newsletter.

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!

Get our RSS Feed!

Sponsors

Related Posts

Leave a Reply


* = required fields

(will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


  

CommentLuv Enabled