遍历文件夹下所有文件,一般可以使用opendir 与 readdir 方法来遍历。
代码:
$path = dirname(__FILE__); // __FILE__文件的完整路径和文件名。
// echo __FILE__; // F:\wamp\www\php20190214\index.php
// echo $path; // F:\wamp\www\php20190214
$result = traversing($path);
var_dump($result);
function traversing($path) {
$result = array();
if ($handle = opendir($path)) {
while ($file = readdir($handle)) {
if ($file != '.' && $file != '..') {
if (strtolower(substr($file, -4)) == '.php') {
array_push($result, $file);
}
}
}
}
return $result;
}
// array (size=16)
// 0 => string '1.php' (length=5)
// 1 => string '2.php' (length=5)
// 2 => string '3.php' (length=5)
// 3 => string 'ajax.php' (length=8)
// 4 => string 'conn.php' (length=8)
?>
如使用glob方法来遍历则可以简化代码:
$path = dirname(__FILE__);
$result = glob($path.'/*.php');
var_dump($result);
// array (size=16)
// 0 => string 'F:\wamp\www\php20190214/1.php' (length=29)
// 1 => string 'F:\wamp\www\php20190214/2.php' (length=29)
// 2 => string 'F:\wamp\www\php20190214/3.php' (length=29)
// 3 => string 'F:\wamp\www\php20190214/ajax.php' (length=32)
// 4 => string 'F:\wamp\www\php20190214/conn.php' (length=32)
?>
注意,glob返回的会是path+搜寻结果的路径,例如path=’/home/fdipzone’,
这是与opendir,readdir返回的结果不同的地方。
如果只是遍历当前目录。可以改成这样:glob(‘*.php’);