Jump to content

How do I show the number of files in a folder/directory?


ethan89

Recommended Posts

I've tried this code and a few others, but it only displays 0.  I'd like the simplest working way to display the number of files in a directory.  Thanks for the help!

 

$directory = "../images/team/harry/";

$filecount = count(glob("" . $directory . "*.*"));

echo $filecount;

Not sure if it's the proper way to do this, but here goes:

 

<?php
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        $thefiles = array();
        if ($file != "." && $file != "..") {
            array_push($thefiles, $file);
        }
    }
    closedir($handle);
}
$filecount = count($thefiles); //echo $filecount should give you the number of files in your directory. 
?>

 

Not exactly, or anywhere near what I originally put, but this worked for me and it will give you the number of directories in your directory as well, if you wish. If not just delete that part out, I suppose.

 

<?php
$path = '/path/to/dir';
$numfile = 0;
$numdir = 0;
if ($handle = opendir($path)) {
	while (false !== ($file = readdir($handle))) {
		if ($file != "." && $file != "..") {
			$fName = $file;
			$file = $path.'/'.$file;
			if(is_file($file)) $numfile++;
			if(is_dir($file)) $numdir++;
			};
		};
		closedir($handle);
	};
echo $numfile.' files in a directory';
echo $numdir.' subdirectory in directory';
?> 

Thanks!  It works perfectly!  I removed the number of directories parts of the code and made it shorter.  Here is my final code:

 

<?php

$path = '.';

$no = "0";

if ($handle = opendir($path))

{

while (false !== ($img = readdir($handle)))

{

if ($img != "." && $img != ".." && $img != "index.php")

{

$img = $path.'/'.$img;

if (is_file($img)) $no++;

}

}

closedir($handle);

}

echo "$no";

?>

 

SOLVED, Thanks phobic

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.