php遍歷文件夾方法
原理
- 遞歸獲取
/**
* 獲取目錄下文件夾列表(遞歸).
*
* @param string $dir 目錄
*
* @return array 文件夾列表(遞歸函數返回的是路徑的全稱,和非遞歸返回的有區別)
*/
function GetDirsInDir_Recursive($dir)
{
$dirs = array();
if (!file_exists($dir)) {
return array();
}
if (!is_dir($dir)) {
return array();
}
$dir = str_replace('\\', '/', $dir);
if (substr($dir, -1) !== '/') {
$dir .= '/';
}
if (function_exists('scandir')) {
foreach (scandir($dir, 0) as $d) {
if (is_dir($dir . $d)) {
if (($d != '.') && ($d != '..')) {
$array = GetDirsInDir($dir . $d);
if (count($array) > 0) {
foreach ($array as $key => $value) {
$dirs[] = $dir . $d . '/' . $value;
}
}
$dirs[] = $dir . $d;
}
}
}
} else {
$handle = opendir($dir);
if ($handle) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if (is_dir($dir . $file)) {
$array = GetDirsInDir($dir . $file); //此方法在下面,請往下看
if (count($array) > 0) {
foreach ($array as $key => $value) {
$dirs[] = $dir . $file . '/' . $value;
}
}
$dirs[] = $dir . $file;
}
}
}
closedir($handle);
}
}
return $dirs;
}
/**
* 獲取當前目錄下文件夾列表.
*
* @param string $dir 目錄
*
* @return array 文件夾列表
*/
function GetDirsInDir($dir)
{
$dirs = array();
if (!file_exists($dir)) {
return array();
}
if (!is_dir($dir)) {
return array();
}
$dir = str_replace('\\', '/', $dir);
if (substr($dir, -1) !== '/') {
$dir .= '/';
}
// 此處的scandir雖然是PHP 5就已加入的內容,但必須加上兼容處理
// 部分一鍵安裝包的早期版本對其進行了禁用
// 這一禁用對安全沒有任何幫助,推測是早期互聯網流傳下來的“安全祕笈”。
// @see: https://github.com/licess/lnmp/commit/bd34d5c803308afdac61626018e4168716d089ae#diff-6282e7667da1e2fc683bed06f87f74c1
if (function_exists('scandir')) {
foreach (scandir($dir, 0) as $d) {
if (is_dir($dir . $d)) {
if (($d != '.') && ($d != '..')) {
$dirs[] = $d;
}
}
}
} else {
$handle = opendir($dir);
if ($handle) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if (is_dir($dir . $file)) {
$dirs[] = $file;
}
}
}
closedir($handle);
}
}
return $dirs;
}