Actually the question: you need to PHP to count the number of files in the folder. Correction: read only files, excluding subfolders.
|
5 answers
For example:
$dir = opendir('path/to/dir'); $count = 0; while($file = readdir($dir)){ if($file == '.' || $file == '..' || is_dir('path/to/dir' . $file)){ continue; } $count++; } echo 'Количество файлов: ' . $count;
- $ file is the name of the file. extension, so you can filter on the desired type. - Dem
- unless he considers only files, but not files and folders? - knes
- Sorry, added check on the folder - Dem
- '.' and '..' are also folders, i.e. verification is superfluous. There is another question - is it correct to consider links, sockets, etc. as files. On sh in * nix I would write if [-f $ file]; then cnt =
expr $cnt + 1
fi - avp
|
I think you can make it even easier.
echo count(scandir('/folder/'));
- "scandir - Get a list of files and directories" - from php.net. Only files can not be selected - Dem
- Pass the array through the additional filter, that's the whole problem. - Arni
- If there are a lot of files and folders in the folder, the version with
scandir
too resource-intensive, unlikeopendir
- Hit-or-miss
|
Taken from here https://stackoverflow.com/questions/12801370/count-how-many-files-in-directory-php
$fi = new FilesystemIterator("/path/to/folder", FilesystemIterator::SKIP_DOTS); printf("Всего файлов: %d", iterator_count($fi));
- Considering that the issue has already started for the eighth year, your reaction rate is not very high. - freim
- I now have a broader task: count the number of files, their sizes, the date of the oldest and the newest, so I myself used iteration based on the results of
glob(rtrim($path, '/') . '/*', GLOB_NOSORT)
- Sergey Beloglazov - Below, @ustatos provided interesting statistics that show exactly what filesystemIterator provides for the fastest result. Now I went to the console, subjectively, 'ls' was executed instantly, 'ls -l' 0.5-1 c on a couple of dozen files. Apparently, receiving file attributes is quite a long operation - Sergey Beloglazov
|
$cfiles = count(array_diff(scandir("/path/to/folder"), [".", ".."])); printf("Всего файлов: %d", $cfiles);
- Please give a brief explanation of the code. - 0xdb
|
Another option with an iterator and some statistics
While: 0.42448782920837 FilesystemIterator 0.0074279308319092 DirectoryIterator: 0.77696204185486 echo countFile(__DIR__); function countFile($dir) { $iterator = new DirectoryIterator($dir); $count = 0; iterator_apply( $iterator, 'isFile', [$iterator, &$count] ); return $count; } function isFile(Iterator $item, int &$count) { if ($item->isFile()) { $count++; } return true; }
|