Monday, January 25, 2010

Recursive file/folder tree

<?php
function create_tree($dir)
{
 if ($handle = @opendir($dir))
 {
  $i=0;
  while (false !== ($file = @readdir($handle)))
  {
   if ($file != '.' && $file != '..')
   {
   $list[$i]=$file;
   $i++;
   }
  }
  $dir_length = count($list);

  for($i=0;$i<$dir_length;$i++)
  {
   if(strrpos($list[$i], '.') == FALSE)
   {
    echo '
  • '.$list[$i].'
      '; create_tree($dir.'/'.$list[$i]); echo '
  • '; } else { echo '
  • '.$list[$i].'
  • '; /* I REALIZE THE HREF ATTRIBUTE ABOVE LOOKS QUOTED WEIRD BLOGGER KEEPS OVERRIDING NESTED QUOTES FOR SOME REASON */ } } closedir($handle); } } $dir = '/'; echo '
      '.dirname($dir).'
    • '.basename($dir).'
        '; create_tree($dir); echo '
    '; ?>