hai friends

I need to count the files with in the selected folder.

How to count the files ?? please help me. If any paossibel ple4ase send me sample code.

Thanks
vssp

hai friends

I need to count the files with in the selected folder.

How to count the files ?? please help me. If any paossibel ple4ase send me sample code.

Thanks
vssp

I wrote a directory reading class in my blog that you could look at:
http://fijiwebdesign.com/content/view/83/77/

Heres how you would count the number of files in a directory using the class in the link above:

/**
* Use the readDir class to count files in the directory
*/

$dir_path = '/my/directory/path'; // change to the directory path

$dir = new readDir(); // instantiate our class
$file_count = 0;

// set the directory to read
$dir->setPath( $dir_path );

// we do not want to read sub folders
$dir->readRecursive(false); 

// set a function to call when a new dir is read
$dir->setEvent( 'readDir_file', 'increment_file_count' );

// read the dir
if ( !$dir->read() ) {
    die($dir->error());
} 

// our custom function called when a new file is read
function increment_file_count($path, $filename) {
	global $file_count;
	
	$file_count++; // increment file count
  
}

echo $file_count; // this is the number of files in the directory $dir_path

Should be quite self explanatory.

If you'd rather go with using the regular php functions, heres an example:

/**
* Count files or sub-directories in a directory
* @author digital-ether at fijiwebdesign.com
*
* @param string directory path
* @param string element type to count (file|dir)
*/
function count_dir_elements($dir_path, $type = 'file') {
	$file_count = 0;
	$dir_count = 0;
	if ($dh = opendir($dir_path)) {
		$i = 0;
		while ($el = readdir($dh)) {
			$path = $dir.'/'.$el;
	
			if (is_dir($path) && $el != '.' && $el != '..') {
				$dir_count++;
			} elseif (is_file($path)) {
				$file_count++;
			}
			$i++;
		}               
	   closedir($dh);
	} else {
		return false;
	}
	return $type == 'file' ? $file_count : $dir_count;
}

// eg: count the files in this directory

echo count_dir_elements(dirname(__FILE__), $type = 'file');
This article has been dead for over six months. Start a new discussion instead.