Web Hosting Talk







View Full Version : Counting Files in a directory


QuadVods
05-21-2006, 01:24 PM
Hi,

I'm using this script to count the number of files in a directory (e.g. I want to display: '10 Files hosted')

The problem is that this code is returning '0' as the count, which is wrong.

The index page in the root will have the counter (www.domain.com (http://www.domain.com))

the directory with the files in is www.domain.com/1 (http://www.domain.com/1)


//get path of directory containing this script
$dir = $_SERVER['DOCUMENT_ROOT'].dirname("/1/");
//open a handle to the directory
$handle = opendir($dir);
//intitialize our counter
$count = 0;
//loop through the directory
while (false !== ($file = readdir($handle))) {
//evaluate each entry, removing the . & .. entries
if (is_file($file) && $file !== '.' && $file !== '..') {
$count++;
}
}
echo $count;


Any help would be much appreciated!

jabab
05-21-2006, 02:42 PM
Try $dir = $_SERVER['DOCUMENT_ROOT']."/1/";

QuadVods
05-21-2006, 02:55 PM
Sorted...

moved the $count++ outside the if statement

and changed the $dir= works now!

orbitz
05-21-2006, 03:16 PM
Sorted...

moved the $count++ outside the if statement

and changed the $dir= works now!

Your change does not make sense. If you put the count outside the if, then you don't need the if statement.


if (is_file($file) && $file !== '.' && $file !== '..') {
$count++;
}



You have used the wrong syntax - it should've been: '!=' , not '!=='

change your code to this and still keep the count inside the if. This means that it does not count the '.' and '..' as a file.

if ($file != '.' && $file != '..') {
$count++;
}

Burhan
05-22-2006, 02:45 AM
You can also just do this, which works out to be much simpler:


$listing = glob("/1/*.*");
echo 'Number of files : '.sizeof($listing);