How to Count Number of Files in directory PHP?

Today, We want to share with you php count files in directory.In this post we will show you php glob, hear for Count files recursively we will give you demo and example for implement.In this post, we will learn about PHP Lartavel File Counter PHP Script with an example.

Count how many files in directory PHP

If you are working on code php server side and you require to count number of files, directory, images like as a jpg, png, gif, zip file, rar files, etc in the given folder path, then you can count using glob() and count() of php. So, let’s see this bellow example and learn how it done.
Example 1:

$folderPath = "upload/";

$totalCountAllFiles = 0;

$getAlltotalFiles = glob($folderPath . "*");

if ($getAlltotalFiles){

 $totalCountAllFiles = count($getAlltotalFiles);

}

echo "<pre>";
print_r($totalCountAllFiles);

PHP: How to count files in folder?

Example 2:

$folderPath = '/var/www/api';
$file = glob($folderPath . '*');
$totalCountAllFiles = 0;
if ($file != false)
{
    $totalCountAllFiles = count($file);
}
print_r($totalCountAllFiles);

Write a PHP program that counts the total number of files in a directory?

Read Also:  Laravel set global Variable in middleware, all controller and views

<?php
 
echo totalCountAllFiles("/home/api");
 
function totalCountAllFiles($path) {
  $size = 0;
  $ignore = array('.','..');
  $files = scandir($path);
  foreach($files as $t) {
    if(in_array($t, $ignore)) continue;
    if (is_dir(rtrim($path, '/') . '/' . $t)) {
      $size += totalCountAllFiles(rtrim($path, '/') . '/' . $t);
    } else {
      $size++;
    }   
  }
  return $size;
}
 
?>

Results:

$ php index.php
6925

I hope you get an idea about php count number of files in directory.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Read Also:  Shorthand comparisons in Laravel Ternary Operators (?:)

About Pakainfo

I am Jaydeep Gondaliya, a software engineer, the founder and the person running Pakainfo. I'm a full-stack developer, entrepreneur and owner of Pakainfo.com. I live in India and I love to write tutorials and tips that can help to other artisan, a Passionate Blogger, who love to share the informative content on PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Pakainfo →

Leave a Reply

Your email address will not be published. Required fields are marked *