Home  >  Article  >  Backend Development  >  How to count the number of files in a PHP directory?

How to count the number of files in a PHP directory?

藏色散人
藏色散人Original
2019-03-04 16:49:042811browse

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.

How to count the number of files in a PHP directory?

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} 来匹配 &#39;a&#39;,&#39;b&#39; 或 &#39;c&#39;
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn