Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

PHP Script To Count Folders?

Status
Not open for further replies.

mossc001

Technical User
Dec 22, 2004
12
0
0
GB
I have be looking through the internet for a PHP script which counts the number of folders in a given directory but can't find a thing.

Does anyone know of a small script that could be used to count folders and display the output?

<?
$dir="folder/"

Something.....??????

?>

<?php
//Number of folders

echo "Total Folders: ".$totalnofolders."";

?>

Any help would be much appreciated.
Cheers
 
If your version of PHP is 4.3.3 or greater, or if you are running any recent version of PHP on an operating system that uses the GNU C library:


Code:
<?php
$a = count(glob('folder/*', GLOB_ONLYDIR));
print $a;
?>

Want the best answers? Ask the best questions!

TANSTAAFL!!
 
Brilliant!

That is so simple, I don't know why I didn't think of it.

Cheers!!
 
Have you looked at opendir() in The php.net online manual

Of the top of my head it would be something like:
Code:
function count_dirs($path){
//check that $dir really exists
    if(is_dir($path)){
//initialize counter
    $num_dirs="0";
//Open Dir to parse
    if ($dh = opendir($path))
    {
        //begin loop to read directory
        while (($objectindir = readdir($dh)) !== false){
            //discard . and .. directory pointers
             if (($objectindir != ".") && ($objectindir != ".."))
             {
		if(isdir($objectindir))
		{
			//check if name is a dir and increase counter
			$num_dirs++;             
		}

             }//if . and ..
          }//while
    }
    closedir($dh);

return $num_dirs;
}

Notice: this is off the top of my head it could have and most likely does have some errors.



----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top