Jump to content

File Count


Recommended Posts

Hello,I was wondering how I would go about having a number readout of how many files are in a given directory. Then that number would be displayed in the htm document.Sorry if this sound stupid, but I've never typed anything in PHP before.Thanks,-Joe

Theres a couple different ways to do this. The best way for me to do it is with popen(). If your using linux, you can use my code.
$totalFiles = -1;$handle = popen("ls path_to_your_directory_from_root", "r");while(!feof($handle)){	$line = fgets($handle);	$totalFiles ++;}

The popen runs the linux command ls for the directory in right mode. Then the while statement gets each line from that command and adds 1 to the counter. To get an acurate count, I had to set the counter to start at -1 (I'm not really sure why). You could also use opendir() and readdir() like so:

$totalFiles = 0;$dirname = "relative_path_to_your_directory";$dh = opendir($dirname) or die("I can't find $dirname");while (!(($file = readdir($dh)) === false)){   if (is_file("$dirname/$file")){       $totalFiles ++;   }}closedir($dh);

This one works better on Windows.

Link to comment
Share on other sites

What code did you use?

I used the second code aliendisaster posted.Also, the php version installed is: 4.3.11
<?php $totalFiles = 0;$dirname = "test01";if(!($dh=opendir($dirname))) die("Couldn't find ".$dirname);while (!(($file = readdir($dh)) === false)){  if (is_file("$test01/$file")){      $totalFiles ++;  }}closedir($dh);?>

I changed it to that.Then, I made the index file have:

<a href="01122.htm"><?php echo "$totalFiles"; ?></a>

Everything seems to be fine, but the link always shows up as 0, no matter if I add files to the dir or not.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...