Jump to content

[SOLVED] Reading directory--multiple sub directory and displaying


~n[EO]n~

Recommended Posts

Hi ,

I am trying to read directory, multiple sub directory and display the result., but it is not working anyone got a better idea

 

The main directory is templates, it lists that well

inside templates there are other sub directory (all contains 2-3 directory under them) and inside the last directory there is index.html page. I want to list (only name) that page and give a link to that.

 

I tried this but it gives error

Warning: readdir(): 2 is not a valid Directory resource in C:\wamp\www\open_template\open_cms.php on line 8

 

Warning: closedir(): 2 is not a valid Directory resource in C:\wamp\www\open_template\open_cms.php on line 23

<?php
$mydir = "templates";

if ($handle = opendir($mydir)) 
{
    
    while (false !== ($file = readdir($handle))) 
{
        echo "$file <BR>";
	#second step....
	if ($handle2 = opendir($file))
	{
	while (false !== ($file2 = readdir($handle2)))
	{
	echo "   $file <BR>";
	}
	closedir($handle);
	}
	#end of second step...
}

    closedir($handle);
}
?>

 

Any help  ;D

Link to comment
Share on other sites

You need to use recursion.

 

<?php

  function myread($dir) {
    foreaach(scandir($dir) as $file) {
      if (!$file == '.' || !$file == '..') {
        if (is_dir($file)) {
          myread($file);
        } else {
          echo $file;
        }
      }
    }
  }

  myread('templates');

?>

(not tested)

Link to comment
Share on other sites

These were written as tutorials for my site and were never cleaned off, so...

 

Here's a long winded class way of doing it:

class dirbasic
{
function dirbasic($dir=null)
{
	$this->data = null;

	if($dir != null)
	{
		$this->data = $this->make_dir_struct();
		$this->data = $this->dir_fill($this->data, $dir);
	}
}

function set($dir)
{
	if($dir != null)
	{
		$this->data = $this->make_dir_struct();
		$this->data = $this->dir_fill($this->data, $dir);
	}
}

function dir_fill($data, $dir, $parent='')
{
	$data['name'] = $dir;
	$base = $parent.$dir;
	if(strcmp($base[strlen($base)-1], '/')!=0)
	{
		$base .= '/';
	}

	$dirs=opendir($base);
	while (($e=readdir($dirs))!==false)
	{
		if( (strcmp($e, '.') == 0) || (strcmp($e, "..") == 0) )
		{
			continue;
		}
		elseif(is_dir($base.$e))
		{
			$le = $this->make_dir_struct();
			$le = $this->dir_fill($le, $e, $base);
			$data['dirs'][] = $le;
		}
		else
		{
			$a = stat($base.$e);
			$data['files'][] = array($e, $a[7], $a[9]);	//	name, size, modtime
		}
	}
	sort($data['dirs']);
	sort($data['files']);
	return $data;
}

function make_dir_struct()
{
	return array('name' => '', 'dirs' => array(), 'files' => array());
}

function print_dirs()
{
	if($this->data != null)
	{
		$this->print_dir($this->data);
	}
}

function print_dir($data, $spacer='')
{
	$spacer .= '   ';
	print $spacer."<b>".$data['name']."</b><br>";

	foreach($data['dirs'] as $e)
	{
		$this->print_dir($e, $spacer);
	}

	foreach($data['files'] as $e)
	{
		$size = $e[1];
		print $spacer."   ".$e[0]."   ".$size."   ".date("d/m/Y H:i:s", $e[2])."<br>";
	}
}
}


$dir = "../";

$d = new dirbasic();
$d->set($dir);
$d->print_dirs();

 

This generates links as well:

<html>
<head>
<style type="text/css">
a:link { color:#414151; font-size: 11px; text-decoration: none; }
a:active { color:#414151; font-size: 11px; text-decoration: none; }
a:visited { color:#414151; font-size: 11px; text-decoration: none; }
a:hover { color:#5555dd; font-size: 11px; text-decoration: none; cursor: pointer;}
</style>
</head>
<body>
<?php
function getdir($base)
{
$f = array();
$d = array();
$dirs=opendir($base);
while (($dir=readdir($dirs))!==false)
{
	if( (strcmp($dir, '.') == 0) || (strcmp($dir, "..") == 0) )
	{
		continue;
	}
	elseif(is_file($base.$dir))
	{
		$f[] = $base.$dir;
	}
	else
	{
		$d[] = $base.$dir;
	}
}
sort($d);
sort($f);
return array_merge($d, $f);
}

function traverseDirTree($base,$fileFunc,$dirFunc=null,$afterDirFunc=null)
{
$dirs = getdir($base);

foreach($dirs as $path)
{
	if (is_file($path))
	{
		if ($fileFunc!==null)
		{
			$fileFunc($path);
		}
	}
	else
	{
		if ($dirFunc!==null)
		{
			$dirFunc($path);
		}

		if (($subdirectory!='.') && ($subdirectory!='..'))
		{
			traverseDirTree($path.'/',$fileFunc,$dirFunc,$afterDirFunc);
		}

		if ($afterDirFunc!==null)
		{
			$afterDirFunc($path);
		}
	}
}
}

function dodir($path)
{
$level=substr_count($path,'/');
for ($i=1;$i<$level;$i++)
{
	echo '   ';
}
echo "<b>".basename($path)."</b><br>";
}

function dofile($path)
{
$level=substr_count($path,'/');
for ($i=1;$i<$level;$i++)
{
	echo '   ';
}
echo "<a href='".$path."' target='dl'>".basename($path)."</a><br>";
}

traverseDirTree('../','dofile','dodir');
?>
</body>
</html>

 

Have fun...

Link to comment
Share on other sites

When i keep default (as you gave) it shows

Config.Msi

Documents and Settings

Administrator folders etc...

 

when i keep

traverseDirTree('/','dofile','dodir');

it shows the same

 

and keeping blank gives error

traverseDirTree(' ','dofile','dodir');

Warning: readdir(): supplied argument is not a valid Directory resource in C:\wamp\www\open_template\open_cms.php on line 17

 

BTW, i want to show directory inside the folders not from outside

My folder is this

open_template

  -- templates

      -- thunder

            -- thunder

              -- index.html

      -- the wild

        -- same as above

 

i want to list the directory inside templates and my OS is Win XP

 

Thanks

 

Link to comment
Share on other sites

The default wouldshow from the parent directory '../' (that's what that means).

When you pass an empty string you could put this in (see first example),

if(strcmp($base[strlen($base)-1], '/')!=0)
{
$base .= '/';
}

That'll prevent it ever being empty, in case some does pass an empty string.

 

I've just had a look at my local copy of this and it does put the inner directories in the right places, all sorted (dirs first, with sub files, dirs etc) and lot! So i'm unclear as to your problem. My dirs show as you've shown that you want...

 

By all means it should work as one would expect?

 

P.S. The first example returns (holds) a data set which you can print out as you want (basic print inc)

Link to comment
Share on other sites

Ok , i got the first one working. Thanks a lot...

 

One more thing i need to ask, now i got the directory listed as i want like below, i don't want to show that images folder and files inside it , in which part i need to add the code, i am not familiar with class and functions...

 

thunder

        thunder

            thunder

              images

                  img1.gif

                  img2.gif

                  img3.gif

                  img4.gif

                  img5.gif

                  img6.gif

                  spacer.gif

              default.css

              index.html

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.