Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Using PHP5 DirectoryIterator to return all files and folders in a directory

Posted on 2007-12-05
14
Medium Priority
?
525 Views
Last Modified: 2010-04-21
I've looked for answers, but none of those I found had the "simple" answer I'm looking for.

I have a directory on my web server that contains both files and sub-directories with files in them as well.
I would like to build a tree-like structure from the top directory on down and I understand that the DirectoryIterator class will do this, but I just don't understand enough PHP to pull a function together to do this.

I would like to get all files and sub-folders and their contents back in an array if possible so that I can create my own HTML output in a tree-like manner.  I would like to get information for the files that are returned, such as type, size, filename as well.  Can someone share the code for this using the DirectoryIterator class?

thanks
0
Comment
Question by:mamuscia
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 7
14 Comments
 
LVL 10

Accepted Solution

by:
wildzero earned 2000 total points
ID: 20416472
http://www.jellyandcustard.com/2006/05/18/using-directoryiterator-to-list-files-in-php/

Have you seeen that? Going by that it looks faily straight forward. It even shows got to get the filename and size there. And there are built in function to check isDir and isFile.

You able to work from that?
0
 
LVL 10

Expert Comment

by:wildzero
ID: 20416538
I have set it so it stops after 3 (see the limit)
Enjoy
<?PHP
 
	$arr = array();
	$limit = 0;
	ProcessFolder('/path/to/your/folder/');
	
	echo "<pre>";
	print_r($arr);
	echo "</pre>";
	
	
	
	
	Function ProcessFolder($folder='')
	{
		global $arr,$limit;
		$limit++;
		
		//-- End if no folder is given.
		If ($folder == '')
			return false;
 
			
		$dir = new DirectoryIterator( $folder );
		foreach($dir as $file ) 
		{
			If ($file->isDir() && !$file->isDot()) {
 
				If ($limit < 3)
					ProcessFolder($file->getPathname());
				
			} elseif ($file->isFile() && !$file->isDot()) {
				
				$filearr = array('Filename:' => $file->getFilename(), 
												'Size:' =>number_format(($file->getSize()/1024),2)." Kb",
												'Date Created:' => date("D d M Y H:i:sa",$file->getCTime())
											 );
 
				//-- Add file to the array
				$arr[$file->getPath()][] = $filearr;											 
		  }
		  
		} 
		unset($dir);
		
	}
 
?>

Open in new window

0
 
LVL 10

Expert Comment

by:wildzero
ID: 20416541
Bah! the code snippit formatting looks terrible lol
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:mamuscia
ID: 20416568
I tried the code there and it does not produce any results.  I tried changing the directory a few times to different values and still nothing.  If I can get this to work, it should provide what I'm looking for.
<?php
      error_reporting(E_All);
      $dir = new DirectoryIterator( './zones' );
      foreach($dir as $file )
      {
        if(!$file->isDot() && !$file->isDir()) {
            if ($file->isDir()) {
                echo "Directory: ".$file->getFilename();
            }
            else {
            //if ($file->isFile()) {
                echo "FileName: ".$file->getFilename();
                echo "Size: ".number_format(($file->getSize()/1024),2)." Kb";
                echo "Date Created: ".date("D d M Y H:i:sa",$file->getCTime());
                echo "Type: ".$file->getType();
            }
        }
      }
?>

Open in new window

0
 
LVL 10

Expert Comment

by:wildzero
ID: 20416576
hmm the code I wrote based off that site worked fine
using PHP 5.2.5

$dir = new DirectoryIterator( './zones' );

perhaps set that to the full path ie
'/right/from/root/of/the/server/'
0
 

Author Comment

by:mamuscia
ID: 20416607
OK, OK....I set the directory wrong.  It's now working.  I also changed the IF statement to remove the check for isDir so it only checks on the first IF for !isDot().  That way, the IF's below check if it's a file or directory.
It's working great now.

By the way WILDZERO I tried your code too and it works.   I am going to split the points with each of you if you don't mind.  Thanks for your quick replies.  
0
 

Author Comment

by:mamuscia
ID: 20416614
Oops.....I meant you'll get all the points.
0
 
LVL 10

Expert Comment

by:wildzero
ID: 20416615
>>  I am going to split the points with each of you if you don't mind.

lol, it was just me that replied :P
0
 

Author Closing Comment

by:mamuscia
ID: 31413011
Nice!
0
 
LVL 10

Expert Comment

by:wildzero
ID: 20416618
Thanks :-)
0
 

Author Comment

by:mamuscia
ID: 20416706
Yeh, I saw MASTER and mis-interpretted it for another ID....:-)
0
 

Author Comment

by:mamuscia
ID: 20416934
Hey Wildzero if you or anyone else is still listening.  The function I use stops at the first level directory and does not retrieve files and folders below where I point it.  Do you know of anything that would limit the recursion to just one level?  For example, if I point it at "./", it retrieves just the files and directory names found in that directory, but does not open all directories to look inside of them.  Do you know what I have to do to get all files and folders from a given directory - AND all of their children file and folders, etc?  Thanks.
0
 
LVL 10

Expert Comment

by:wildzero
ID: 20417062
yes, see my code - it did recurrision
0
 

Author Comment

by:mamuscia
ID: 20419261
I see that, thanks again.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

721 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question