Page 1 of 1

php file count inc subdirectories

Posted: Sat Mar 22, 2008 7:52 am
by thebluebus
hi, wondered if you may be able to help me.
I'm trying to write a php script to count the number of files within a folder and its subdirectories

Code: Select all

<?php
$count = 0;
foreach( glob( "images/*.*" ) as $filename ) {
$count++;
}
echo $count;
?>
but it only counts files in the one folder. How do i make it include subdirectories?

thanks :D

Re: php file count inc subdirectories

Posted: Sat Mar 22, 2008 9:36 am
by vigge89
You can either use a recursive function which grabs all subnodes (files/folders) of the specified path and returns them as an array, or use some kind of a queue array which you iterate through and append paths to folders as you encounter them.
Use is_dir($path) to determine whether a path points to a existing directory or not, if it returns true you've found a directory and should process it accordingly.

Hope that was clear enough, I'm a bit tired at the moment :?

Re: php file count inc subdirectories

Posted: Sat Mar 22, 2008 10:05 am
by mVeliki
Pack that foreach loop into function called, for example EnumerateDir($where), and put "global $count;" at begining.
Use variable $where instead of string "images", and call this func from main script with:
EnumerateDir('images');

Now you can insert before "$count++" following:
if ( (substr($filename,0,1)=='.') and is_dir($where.'/'.$filename) )
EnumerateDir($where.'/'.$filename);


This will enter deeper in subdirectory if ist name doesnt start with dot (hidden dirs).