» Birthday Bundle - Over $400 worth of Envato files for just $20

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!

Get our RSS Feed!

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>

Note: If you want to post CODE Snippets, please make them postable first!
(e.g. <br /> should be converted to &lt;br /&gt;)