getting all sub-directories

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

I'm using PHP 4.4.4 with Apache 2 on Fedora Core 6 Linux.  Given a
directory, how would I get all sub-directories?  I found "scandir" but
that only applies for PHP 5 and I think it returns both files and
folders, whereas I only want the folders.

Thanks for any help, - Dave

Re: getting all sub-directories

This function will do it:

function getFilesByType($dir, $type = 'dir')
  if (($dh = opendir($dir)) === false)  {
    trigger_error('opendir', E_USER_ERROR);
  } else {
    if ($dir[strlen($dir) -1] ==  DIRECTORY_SEPARATOR) {
      $sep = '';
    } else {
    $list = array();
    while (($ent = readdir($dh)) !== false) {
      if ($ent == '.' || $ent == '..') continue;
      if (filetype("$dir$sep$ent") == $type) {
        $list[] = "$dir$sep$ent";
    return $list;
  return false;

On Feb 10, 8:00 pm, ""
Quoted text here. Click to load it

Re: getting all sub-directories


Quoted text here. Click to load it

PHP 4 is dead, PHP 6 on the rise. It's time for an update.

Quoted text here. Click to load it

I suggest to update to PHP 5 and use the iterators from the SPL. Then
with a simple 'foreach' loop you can easily loop through arbitrarily
deep nested tree structures and search for whatever you like, e.g.

$result = array();
foreach (new DirectoryIterator($yourPath) as $item) {
  if ($item->isDir() && !$item->isDot()) {
    $result[] = $item->getPathname();


Site Timeline