Solved

PHP Code : How to scan a folder for all folders in it and then print their sorted names in numbered list ?

Posted on 2008-06-15
9
788 Views
Last Modified: 2010-04-21
Hi

We need to scan a folder for all other folders that a re present in it. It should scan to very deep level of folders.

It then, should print sorted, numbered listed of all folders found.

 It should also ignore default "." & ".." directories.

Thanks,
0
Comment
Question by:theredcode
9 Comments
 
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 21788336
please check out this function:
http://www.bin-co.com/php/scripts/filesystem/ls/
0
 
LVL 4

Expert Comment

by:afzz
ID: 21788343
try this
<?php

function showDirect( $pth = '.', $lev = 0 ){

    $ignore = array( 'cgi-bin', '.', '..' );// Directories to ignore

    $dh = @opendir( $pth );

    while( false !== ( $file = readdir( $dh ) ) ){

        if( !in_array( $file, $ignore ) ){

            $spacer = str_repeat( '&nbsp;', ( $lev * 4 ) );

            if( is_dir( "$pth/$file" ) ){

                echo "<strong>$spacer $file</strong><br />";

                showDirect( "$pth/$file", ($lev+1) );            

            } else {

                echo "$spacer $file<br />";            

            }

        }

    }

    closedir( $dh );

}

 

?> 

 

 

Calling the function

 

 

showDirect( "." );// Current directory

 

showDirect( "./this/directory" );// Show "this/directory"

Open in new window

0
 

Author Comment

by:theredcode
ID: 21788373
not working afzz....

0
 
LVL 4

Expert Comment

by:afzz
ID: 21788405
it will print the directory contents recursively. the spacer variable needs to be modified to output as a list

check this page

http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_23485982.html
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:theredcode
ID: 21788521
still strugling...

cant make numbered list and i also unable to print number of files found in each directory in line under it. Also sorted list.

what i want is...

1. Audio
Files Fould : 5

2. English
Files Fould : 0

3. Audio
Files Fould :8

4. English
Files Fould :1
0
 

Author Comment

by:theredcode
ID: 21788524
sorry in alphabatically sorted list
0
 
LVL 2

Accepted Solution

by:
artzter earned 500 total points
ID: 21791196
funny little mind-game hehe.
spend a few hours trying to make it work yesterday, and heres my result.
The sort-function (sortbyname()) is quite messy and im sure it can be done easier, but it works.

Hope you can use it.
<?php

filefinder();
 

function filefinder() {

	#SELECT THE FOLDER FROM WHERE YOU

	#WILL START SEARCHING

	$topfolderpath = "myfolder";
 

	#DEFINES THE VARIABLES NEEDED

	$tree = array();

	$undone = array();
 

	#IF THIS IS THE FIRST RUN, LETS START WITH

	#THE PATH SPECIFIED

	if(count($tree) == 0) {

		dirsearch($topfolderpath, $tree, $undone);

	}
 

	#FROM NOW ON, WE CAN LET IT LOOP THROUG

	#THE FOLDERS WE HAVE SPOTTED WHILE SCANNING

	#OTHER DIRECTORIES

	while(count($undone) > 0)

	{

		foreach($undone as $id => $dir)

		{

			dirsearch($dir, $tree, $undone);

			unset($undone[$id]);

		}

	}
 

	#THE COMPLETE SET OF FOLDERS IS FOUND, BUT NEED TO BE

	#SORTED BY NAME BEFORE PRINTED.

	sortbyname($tree);
 

	#AT LAST, LETS LOOP THE CONTENT TO THE SCREEN

	foreach($tree as $id=>$element) {

		echo $id + 1 .". ". $element["name"] ."<br />";

		echo "Files found: ". $element["files"]. "<br /><br />";
 

	}

}
 

function sortbyname(&$tree) {

	#DEFINE OUR VARIABLE(S)

	$names = array();
 

	#LETS CREATE A NEW ARRAY, WITH ONLY THE NAMES

	foreach($tree as $elem) {

		$names[] = $elem["name"];

	}
 

	#TIME TOR SORT THE NEW ARRAY WE HAVE.

	#WE NEED TO HAVE IN MIND THAT THE FUNCTION IS

	#CASE-SENSITIVE, SO LETS DO A LITTLE WORKAROUND.

	$lc = array_map('strtolower', $names);

	array_multisort($lc, SORT_STRING, $names);
 

	#WHEN THE NAMES-ARRAY SORTED, ITS TIME TO FIND THE

	#REAL ARRAY SO WE CAN RE-BUILD IT.

	foreach($names as $name)

	{

		foreach($tree as $elem) {

			if($elem["name"] == $name)

				$sorted[] = $elem;

		}

	}

	#OVERWRITES THE EXISTING ARRAY

	$tree = $sorted;

}
 

function dirsearch($dir, &$tree, &$undone) {

	#INITIAL VARS

	$i = count($tree);

	$conn = opendir($dir);

	$files = 0;
 

	#LETS LOOP THROUG ALL THE CONTENT IN THE SELECTED

	#DIRECTORY

    while (false !== ($file = readdir($conn))) {

    	#WE DONT WANT TO HAVE . AND .. LISTED!

    	if($file != "." && $file != "..")

    	{

    		#IS IT A DIR OR A FILE WE FOUND?

    		#IF IT IS A DIR, WE WILL SAVE IT TEMPORARILY

    		#SO WE CAN SEARCH IT LATER.

			if(is_dir($dir ."/". $file)) {

				$undone[] = $dir."/".$file;

			}

			else

			{

				$files++;

			}

		}

    }

    closedir($conn);
 

    #WE DONT WANT ALL THE MESSY PATH INFORMATION PRINTED

    #SO LETS REMOVE IT.

	$shortname = explode("/", $dir);

	$tree[$i]["name"] = $shortname[count($shortname)-1];
 

	#ALMOST DONE, JUST HAVE TO REMEMBER TO SAVE WHAT WE CAME FOR.

    $tree[$i]["files"] = $files;

}

?>

Open in new window

0
 
LVL 49

Expert Comment

by:Roonaan
ID: 21791519
You can use this:
<?php

echo '<ul>';

listFiles('/path/to/my/folder/');

echo '</ul>';
 

function listFiles($dir) {

	$it    = opendir($dir);

	$files = 0;

	$dirs  = array();

	while($f = readdir($it)) {

		if($f == '.' || $f == '..') {

			continue;

		}

		if(is_file($dir.'/'.$f)) {

			$files++;

		} else {

			$dirs[] = $dir.'/'.$f;

		}

	}

	

	echo '<li>'.basename($dir);

	echo '<br />Files Found: '.$files;

	if(count($dirs) > 0) {

		echo '<ul>';

		array_map('listFiles', $dirs);

		echo '</ul>';

	}

	echo '</li>';

}

Open in new window

0
 

Author Closing Comment

by:theredcode
ID: 31467329
Thanks very much
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

This article will explain how to display the first page of your Microsoft Word documents (e.g. .doc, .docx, etc...) as images in a web page programatically. I have scoured the web on a way to do this unsuccessfully. The goal is to produce something …
This article discusses four methods for overlaying images in a container on a web page
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…

706 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now