用老旧的文件和目录读取函数,已经过时了,一般用glob,高效直接。但是glob不能递归获取(或者说我没找到,所以有替代方法)
方法一:(推荐使用)SPL
Those of you with PHP 5 don't have to come up with these wild functions to scan a directory recursively: the SPL can do it.
<?php
$dir_iterator = new RecursiveDirectoryIterator("/path");
$iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);
// could use CHILD_FIRST if you so wish
foreach ($iterator as $file) {
echo $file, "\n";
}
?>
Not to mention the fact that $file will be an SplFileInfo class, so you can do powerful stuff really easily:
<?php
$size = 0;
foreach ($iterator as $file) {
if ($file->isFile()) {
echo substr($file->getPathname(), 27) . ": " . $file->getSize() . " B; modified " . date("Y-m-d", $file->getMTime()) . "\n";
$size += $file->getSize();
}
}
echo "\nTotal file size: ", $size, " bytes\n";
?>
方法二:
if ( ! function_exists('glob_recursive'))
{
// Does not support flag GLOB_BRACE
function glob_recursive($pattern, $flags = 0)
{
$files = glob($pattern, $flags);
foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir)
{
$files = array_merge($files, glob_recursive($dir.'/'.basename($pattern), $flags));
}
return $files;
}
}
来自文档:http://cn2.php.net/manual/en/function.glob.php