Home > Article > Backend Development > How to count the number of files in a PHP directory?
During the project development process, sometimes it is necessary to count files, images, zip files, rar files, etc. in a given folder path, then we can use the glob() and count() functions in php Make a count.
The code example is as follows:
<?php $folderPath = "upload/"; $countFile = 0; $totalFiles = glob($folderPath . "*"); if ($totalFiles){ $countFile = count($totalFiles); } print_r($countFile);
Related function introduction:
glob() functionFind file paths that match pattern
glob ( string $pattern [, int $flags = 0 ] ) : array
glob() function searches for all file paths that match pattern according to the rules used by libc glob() function, similar to the rules used by general shells. No abbreviation expansion or parameter substitution is performed. Returns an array containing matching files/directories. Returns FALSE if an error occurs.
Valid flags for parameter flags are:
GLOB_MARK - 在每个返回的项目中加一个斜线 GLOB_NOSORT - 按照文件在目录中出现的原始顺序返回(不排序) GLOB_NOCHECK - 如果没有文件匹配则返回用于搜索的模式 GLOB_NOESCAPE - 反斜线不转义元字符GLOB_BRACE - 扩充 {a,b,c} 来匹配 'a','b' 或 'c' GLOB_ONLYDIR - 仅返回与模式匹配的目录项 GLOB_ERR - 停止并读取错误信息(比如说不可读的目录),默认的情况下忽略所有错误
count() functionCalculate the number of units in the array, or the number of attributes in the object
count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] ) : int
Count the number of all elements in an array, or things in an object. For objects, if SPL is installed, you can hook count() by implementing the Countable interface. This interface has only one method Countable::count(), which is the return value of the count() function.
This article is an introduction to the calculation method of the number of files in the PHP directory. It is simple and easy to understand. I hope it will be helpful to friends in need!
The above is the detailed content of How to count the number of files in a PHP directory?. For more information, please follow other related articles on the PHP Chinese website!