Return to Snippet

Revision: 18419
at September 30, 2009 00:04 by artoodetoo


Initial Code
<?php

function fillEntries($dir, &$entries, $ext = '')
{
	$l = strlen($ext);
	$d = dir($dir);
	$subEntries = array();

	while (($entry = $d->read()) !== false)
	{
		// skip hidden files, . and ..
		if ($entry{0} != '.')
		{
			if (is_file($dir.'/'.$entry))
			{
				// case insensitive extension test
				if (!$l || strcasecmp(substr($entry, -$l), $ext) == 0)
					$subEntries[] = $entry;
			}
			else
				fillEntries($dir.'/'.$entry, $entries, $ext);
		}
	}
	$d->close();

	if (!empty($subEntries))
		$entries[$dir] =& $subEntries;

	// return count of "leaf" nodes
	return count($entries, COUNT_RECURSIVE) - count($entries);
}

$entries = array();
// NB: extension parameter with dot char
$count = fillEntries('.', $entries, '.zip');
$content = print_r($entries, TRUE);
echo "There are {$count} entries:
<pre>
{$content}
</pre>
";

Initial URL


Initial Description
Sometime it is convenient to get recursive directory listing as array of items
  directory => (file array)
  Such as:

    Array
    (
        [./a2temple] => Array
            (
                [0] => example13.zip
            )
    
        [./rand] => Array
            (
                [0] => rand.zip
            )
    
        [./pstudio] => Array
            (
                [0] => pstudio.zip
            )
    
        [./myview/private] => Array
            (
                [0] => logs.zip
            )
    
        [./myview] => Array
            (
                [0] => myview-2.zip
            )
    
        [.] => Array
            (
                [0] => testutf.zip
                [1] => RBAC.ZIP
            )
    
    )

My function can get optional extension filter and returns count of files found.

Initial Title
Another Directory Crowler

Initial Tags
directory

Initial Language
PHP