Php count files in directory

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 count files in directory

Penny Liu

12.7k5 gold badges69 silver badges86 bronze badges

asked Oct 9, 2012 at 13:38

Bradly SpicerBradly Spicer

2,2065 gold badges22 silver badges34 bronze badges

2

You can simply do the following :

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

answered Oct 9, 2012 at 14:01

Php count files in directory

1

You can get the filecount like so:

$directory = "/path/to/dir/";
$filecount = count(glob($directory . "*"));
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'

Note that glob() skips Linux hidden files, or all files whose names are starting from a dot, i.e. .htaccess.

Php count files in directory

answered Oct 9, 2012 at 13:44

JKirchartzJKirchartz

17.1k7 gold badges59 silver badges87 bronze badges

4

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;

Php count files in directory

answered Oct 9, 2012 at 13:41

intelisintelis

7,36913 gold badges54 silver badges98 bronze badges

5

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>

answered Oct 9, 2012 at 13:42

Php count files in directory

Laurent BrieuLaurent Brieu

3,2511 gold badge13 silver badges14 bronze badges

4

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

answered Feb 18, 2019 at 2:59

4

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)

answered Oct 22, 2013 at 9:29

vbwxvbwx

3886 silver badges12 bronze badges

2

Working Demo

<?php

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

?>

answered Oct 9, 2012 at 13:46

Php count files in directory

Nirav RanparaNirav Ranpara

15.7k4 gold badges42 silver badges57 bronze badges

1

I use this:

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

answered Mar 7, 2014 at 5:45

1

<?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 '..').

answered Apr 9, 2016 at 21:52

Php count files in directory

SpookySpooky

1,16014 silver badges17 bronze badges

2

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)
    )
)

answered Jan 3, 2019 at 19:31

PanniPanni

1903 silver badges14 bronze badges

1

$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.

answered Nov 16, 2015 at 10:32

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 "::"');

answered Aug 17, 2017 at 8:59

Php count files in directory

MichelMichel

3,9384 gold badges35 silver badges50 bronze badges

$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;

answered Oct 16, 2018 at 13:40

0

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.

answered Apr 17, 2020 at 4:44

GTodorovGTodorov

1,85521 silver badges23 bronze badges

  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 ....

answered Jan 2, 2015 at 13:37

parajs dfsbparajs dfsb

1351 gold badge4 silver badges13 bronze badges

1

Not the answer you're looking for? Browse other questions tagged php file count directory or ask your own question.

How can I count the number of files in a directory in PHP?

PHP contains many functions like count(), iterator_count(), glob(), openddir(), readdir(), scandir() and FilesystemIterator() to count number of files in a directory. count() Function: The count() functions is an array function which is used to count all elements in an array or something in an object.

How do I get a list of files in a directory in PHP?

The scandir() function returns an array of files and directories of the specified directory.

How do I count files in current directory?

To determine how many files there are in the current directory, put in ls -1 | wc -l. This uses wc to do a count of the number of lines (-l) in the output of ls -1.

How do I count a file?

The easiest way to count files in a directory on Linux is to use the “ls” command and pipe it with the “wc -l” command..
In order to count files recursively on Linux, you have to use the “find” command and pipe it with the “wc” command in order to count the number of files..