Page 1 of 1

**Code to count # of folders in a directory and display it**

Posted: Tue Oct 21, 2003 5:08 pm
by FormatteD_C
Hi,
I am a complete nub when it comes custom PHP coding, I know how to edit things and what not. Anyway, can someone show me a code that counts the number of folders in a directory on a server and then display the number in text format, I've looked across the net and found nothing, thanks :D

Posted: Tue Oct 21, 2003 5:14 pm
by markl999
Depends on your version of PHP but if you're using PHP >= 4.3.0 then you could do:

Code: Select all

echo count(glob('/path/to/dir/*'), GLOB_ONLYDIR);

Nope

Posted: Tue Oct 21, 2003 5:31 pm
by FormatteD_C
Its version 4.2.3

Posted: Tue Oct 21, 2003 5:43 pm
by markl999
Ah ok, then try this:

Code: Select all

$dirtocount = 'full/path/to/dir/to/count'; //put your directory here
$dircount = 0;
if ($handle = opendir($dirtocount)) {
    while (false !== ($file = readdir($handle))) {
        if(is_dir($dirtocount.'/'.$file)){
            $dircount++;
        }
    }
    closedir($handle);
}
echo $dircount;

:P

Posted: Tue Oct 21, 2003 6:38 pm
by FormatteD_C
I used the script you gave me and I get this line:
Warning: OpenDir: Invalid argument (errno 22) in C:\Webserver\apache\htdocs\update.php on line 35

line 35 is - if ($handle = opendir($dirtocount)) {

/htdocs is the directory with the folders I want it to count

Thanks for helping me out markl999

Posted: Tue Oct 21, 2003 6:42 pm
by markl999
And you have $dirtocount = '/Webserver/apache/htdocs'; ?

I always forget how PHP handles windows paths, wether you need the c:, or backslashes instead of /, or double backslashes likes \\ so try various combinations.

!!!

Posted: Tue Oct 21, 2003 6:46 pm
by FormatteD_C
Works like a charm! Thanks. The path I used was:
'/Webserver/apache/htdocs'