Count how many files in directory PHP

PhpFileCountDirectory

Php Problem Overview


I'm working on a slightly new project. I wanted to know how many files are in a certain directory.

<div id="header">
<?php 
    $dir = opendir('uploads/'); # This is the directory it will count from
    $i = 0; # Integer starts at 0 before counting

    # While false is not equal to the filedirectory
    while (false !== ($file = readdir($dir))) { 
        if (!in_array($file, array('.', '..') and !is_dir($file)) $i++;
    }

    echo "There were $i files"; # Prints out how many were in the directory
?>
</div>

This is what I have so far (from searching). However, it is not appearing properly? I have added a few notes so feel free to remove them, they are just so I can understand it as best as I can.

If you require some more information or feel as if I haven't described this enough please feel free to state so.

Php Solutions


Solution 1 - Php

You can simply do the following :

$fi = new FilesystemIterator(__DIR__, FilesystemIterator::SKIP_DOTS);
printf("There were %d Files", iterator_count($fi));

Solution 2 - Php

You can get the filecount like so:

$directory = "/path/to/dir/";
$filecount = 0;
$files = glob($directory . "*");
if ($files){
 $filecount = count($files);
}
echo "There were $filecount files";

where the "*" is you can change that to a specific filetype if you want like "*.jpg" or you could do multiple filetypes like this:

glob($directory . "*.{jpg,png,gif}",GLOB_BRACE)

the GLOB_BRACE flag expands {a,b,c} to match 'a', 'b', or 'c'

Solution 3 - Php

Try this.

// Directory
$directory = "/dir";

// Returns an array of files
$files = scandir($directory);

// Count the number of files and store them inside the variable..
// Removing 2 because we do not count '.' and '..'.
$num_files = count($files)-2);

Solution 4 - Php

You should have :

<div id="header">
<?php 
    // integer starts at 0 before counting
    $i = 0; 
    $dir = 'uploads/';
    if ($handle = opendir($dir)) {
        while (($file = readdir($handle)) !== false){
            if (!in_array($file, array('.', '..')) && !is_dir($dir.$file)) 
                $i++;
        }
    }
    // prints out how many were in the directory
    echo "There were $i files";
?>
</div>

Solution 5 - Php

The best answer in my opinion:

$num = count(glob("/exact/path/to/files/" . "*"));
echo $num;
  • It doesnt counts . and ..
  • Its a one liner
  • Im proud of it

Solution 6 - Php

Since I needed this too, I was curious as to which alternative was the fastest.

I found that -- if all you want is a file count -- Baba's solution is a lot faster than the others. I was quite surprised.

Try it out for yourself:

<?php
define('MYDIR', '...');

foreach (array(1, 2, 3) as $i)
{
	$t = microtime(true);
	$count = run($i);
	echo "$i: $count (".(microtime(true) - $t)." s)\n";
}

function run ($n)
{
	$func = "countFiles$n";
	$x = 0;
	for ($f = 0; $f < 5000; $f++)
		$x = $func();
	return $x;
}

function countFiles1 ()
{
	$dir = opendir(MYDIR);
	$c = 0;
	while (($file = readdir($dir)) !== false)
		if (!in_array($file, array('.', '..')))
			$c++;
	closedir($dir);
	return $c;
}

function countFiles2 ()
{
	chdir(MYDIR);
	return count(glob("*"));
}

function countFiles3 () // Fastest method
{
	$f = new FilesystemIterator(MYDIR, FilesystemIterator::SKIP_DOTS);
	return iterator_count($f);
}
?>

Test run: (obviously, glob() doesn't count dot-files)

1: 99 (0.4815571308136 s)
2: 98 (0.96104407310486 s)
3: 99 (0.26513481140137 s)

Solution 7 - Php

Working Demo

<?php

$directory = "../images/team/harry/"; // dir location
if (glob($directory . "*.*") != false)
{
 $filecount = count(glob($directory . "*.*"));
 echo $filecount;
}
else
{
 echo 0;
}

?>

Solution 8 - Php

I use this:

count(glob("yourdir/*",GLOB_BRACE))

Solution 9 - Php

<?php echo(count(array_slice(scandir($directory),2))); ?>

array_slice works similary like substr function, only it works with arrays.

For example, this would chop out first two array keys from array:

$key_zero_one = array_slice($someArray, 0, 2);

And if You ommit the first parameter, like in first example, array will not contain first two key/value pairs *('.' and '..').

Solution 10 - Php

Based on the accepted answer, here is a way to count all files in a directory RECURSIVELY:

iterator_count(
    new \RecursiveIteratorIterator(
        new \RecursiveDirectoryIterator('/your/directory/here/', \FilesystemIterator::SKIP_DOTS)
    )
)

Solution 11 - Php

$it = new filesystemiterator(dirname("Enter directory here"));
printf("There were %d Files", iterator_count($it));
echo("<br/>");
    foreach ($it as $fileinfo) {
        echo $fileinfo->getFilename() . "<br/>\n";
    } 

This should work enter the directory in dirname. and let the magic happen.

Solution 12 - Php

Maybe usefull to someone. On a Windows system, you can let Windows do the job by calling the dir-command. I use an absolute path, like E:/mydir/mysubdir.

<?php 
$mydir='E:/mydir/mysubdir';
$dir=str_replace('/','\\',$mydir);
$total = exec('dir '.$dir.' /b/a-d | find /v /c "::"');

Solution 13 - Php

$files = glob('uploads/*');
$count = 0;
$totalCount = 0;
$subFileCount = 0;
foreach ($files as $file) 
{  
    global $count, $totalCount;
    if(is_dir($file))
    {
        $totalCount += getFileCount($file);
    }
    if(is_file($file))
    {
        $count++;  
    }  
}

function getFileCount($dir)
{
    global $subFileCount;
    if(is_dir($dir))
    {
        $subfiles = glob($dir.'/*');
        if(count($subfiles))
        {      
            foreach ($subfiles as $file) 
            {
                getFileCount($file);
            }
        }
    }
    if(is_file($dir))
    {
        $subFileCount++;
    }
    return $subFileCount;
}

$totalFilesCount = $count + $totalCount; 
echo 'Total Files Count ' . $totalFilesCount;

Solution 14 - Php

Here's a PHP Linux function that's considerably fast. A bit dirty, but it gets the job done!

$dir - path to directory

$type - f, d or false (by default)

f - returns only files count

d - returns only folders count

false - returns total files and folders count

function folderfiles($dir, $type=false) {
    $f = escapeshellarg($dir);
    if($type == 'f') {
        $io = popen ( '/usr/bin/find ' . $f . ' -type f | wc -l', 'r' );
    } elseif($type == 'd') {
        $io = popen ( '/usr/bin/find ' . $f . ' -type d | wc -l', 'r' );
    } else {
        $io = popen ( '/usr/bin/find ' . $f . ' | wc -l', 'r' );
    }

    $size = fgets ( $io, 4096);
    pclose ( $io );
    return $size;
}

You can tweak to fit your needs.

Please note that this will not work on Windows.

Solution 15 - Php

  simple code add for file .php then your folder which number of file to count its      
  
    $directory = "images/icons";
	$files = scandir($directory);
	for($i = 0 ; $i < count($files) ; $i++){
		if($files[$i] !='.' && $files[$i] !='..')
		{ echo $files[$i]; echo "<br>";
			$file_new[] = $files[$i];
		}
	}
	echo $num_files = count($file_new);

simple add its done ....

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBradly SpicerView Question on Stackoverflow
Solution 1 - PhpBabaView Answer on Stackoverflow
Solution 2 - PhpJKirchartzView Answer on Stackoverflow
Solution 3 - PhpintelisView Answer on Stackoverflow
Solution 4 - PhpLaurent BrieuView Answer on Stackoverflow
Solution 5 - Phpuser10736793View Answer on Stackoverflow
Solution 6 - PhpvbwxView Answer on Stackoverflow
Solution 7 - PhpNirav RanparaView Answer on Stackoverflow
Solution 8 - PhpPhilipp WerminghausenView Answer on Stackoverflow
Solution 9 - PhpSpookyView Answer on Stackoverflow
Solution 10 - PhpPanniView Answer on Stackoverflow
Solution 11 - PhpoussamaView Answer on Stackoverflow
Solution 12 - PhpMichelView Answer on Stackoverflow
Solution 13 - Phpuser3121984View Answer on Stackoverflow
Solution 14 - PhpGTodorovView Answer on Stackoverflow
Solution 15 - Phpparajs dfsbView Answer on Stackoverflow