How can i count the number of files in a directory in php?

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


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.

How can i count the number of files in a directory in php?

Penny Liu

12.8k5 gold badges70 silver badges86 bronze badges

asked Oct 9, 2012 at 13:38

Bradly SpicerBradly Spicer

2,2165 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

How can i count the number of files in a directory in php?

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.

How can i count the number of files in a directory in php?

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;

How can i count the number of files in a directory in php?

answered Oct 9, 2012 at 13:41

intelisintelis

7,37913 gold badges54 silver badges98 bronze badges

5

You should have :


answered Oct 9, 2012 at 13:42

How can i count the number of files in a directory in php?

Laurent BrieuLaurent Brieu

3,2611 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:


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


answered Oct 9, 2012 at 13:46

How can i count the number of files in a directory in php?

Nirav RanparaNirav Ranpara

15.8k4 gold badges42 silver badges57 bronze badges

1

I use this:

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

answered Mar 7, 2014 at 5:45

1


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

How can i count the number of files in a directory in php?

SpookySpooky

1,17014 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("
"); foreach ($it as $fileinfo) { echo $fileinfo->getFilename() . "
\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.

answered Aug 17, 2017 at 8:59

How can i count the number of files in a directory in php?

MichelMichel

3,9784 gold badges36 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 "
"; $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

How do I count the number of files in a 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 get a list of files in a directory in PHP?

The scandir() function in PHP is an inbuilt function that is used to return an array of files and directories of the specified directory. The scandir() function lists the files and directories which are present inside a specified path.

How do I count files in a folder and subfolders?

Use File Explorer Open the folder and select all the subfolders or files either manually or by pressing CTRL+A shortcut. If you choose manually, you can select and omit particular files. You can now see the total count near the left bottom of the window. Repeat the same for the files inside a folder and subfolder too.

How do I count files in CMD?

How to count the files in a folder, using Command Prompt (cmd) You can also use the Command Prompt. To count the folders and files in a folder, open the Command Prompt and run the following command: dir /a:-d /s /b "Folder Path" | find /c ":".