統計目錄下檔案數量是常見需求。本文提供三種不同效能與功能的做法。
<?php
function count_files_opendir($dir) {
if (!is_dir($dir)) return 0;
$count = 0;
$handle = opendir($dir);
while (($file = readdir($handle)) !== false) {
if ($file !== '.' && $file !== '..' && is_file($dir . '/' . $file)) {
$count++;
}
}
closedir($handle);
return $count;
}
?>
<?php
function count_files_glob($dir, $pattern = '*') {
if (!is_dir($dir)) return 0;
$files = glob($dir . '/' . $pattern, GLOB_NOSORT);
// 過濾掉目錄,只計算檔案
return count(array_filter($files, 'is_file'));
}
// 使用範例
echo count_files_glob('/var/www/html'); // 所有檔案
echo count_files_glob('/var/www/html', '*.php'); // 只計 .php 檔案
?>
<?php
function count_files_iterator($dir) {
if (!is_dir($dir)) return 0;
$count = 0;
$iterator = new FilesystemIterator($dir, FilesystemIterator::SKIP_DOTS);
foreach ($iterator as $file) {
if ($file->isFile()) $count++;
}
return $count;
}
// 遞迴計算(含子目錄)
function count_files_recursive($dir) {
$count = 0;
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS)
);
foreach ($iterator as $file) {
if ($file->isFile()) $count++;
}
return $count;
}
?>
| 方法 | 執行時間 | 記憶體 | 備註 |
|---|---|---|---|
| opendir/readdir | ~45ms | 低 | 最基本,相容舊版 PHP |
| glob() | ~60ms | 中(一次載入陣列) | 支援模式,大量檔案記憶體較高 |
| FilesystemIterator | ~35ms | 極低(迭代器逐一產生) | 推薦一般用途 |
| RecursiveIteratorIterator | ~120ms | 低 | 遞迴統計,視深度而定 |
FilesystemIteratorglob()RecursiveIteratorIteratoropendir/readdir