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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
FormatteD_C
Forum Newbie
Posts: 10
Joined: Tue Oct 21, 2003 5:08 pm
Location: Ohio
Contact:

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

Post 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
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post 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);
User avatar
FormatteD_C
Forum Newbie
Posts: 10
Joined: Tue Oct 21, 2003 5:08 pm
Location: Ohio
Contact:

Nope

Post by FormatteD_C »

Its version 4.2.3
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post 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;
User avatar
FormatteD_C
Forum Newbie
Posts: 10
Joined: Tue Oct 21, 2003 5:08 pm
Location: Ohio
Contact:

:P

Post 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
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post 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.
User avatar
FormatteD_C
Forum Newbie
Posts: 10
Joined: Tue Oct 21, 2003 5:08 pm
Location: Ohio
Contact:

!!!

Post by FormatteD_C »

Works like a charm! Thanks. The path I used was:
'/Webserver/apache/htdocs'
Post Reply