How to count the number of files in a directory?

Viewed 7084

I would like to know how to count the number of files in a directory using Laravel 5.2:

$folderPath="upload/";
$countFile=0;
$totalFiles=glob($folderPath."*");
if($totalFiles){
    $countFile=count($totalFiles);
}
print_r($countFile);

this is not working for me.

2 Answers

You can count the number of files in a directory using files or allFiles, as per the 5.6 documentation (though, this feature as been around since 5.0 and your question was specifically regarding 5.2).

The difference between files and allFiles is that allFiles will recursively search sub-directories unlike files. Again, as per the documentation:

The files method returns an array of all of the files in a given directory. If you would like to retrieve a list of all files within a given directory including all sub-directories, you may use the allFiles method:

and the example code that was provided:

use Illuminate\Support\Facades\Storage;

$files = Storage::files($directory);

$files = Storage::allFiles($directory);

Note: This answer has been provided as a more thorough version of an older answer (which pointed me in the right direction, however I personally wanted to confirm that it still worked) with linked documentation / code in the actual answer from the documentation.

Related