Skip to content

Instantly share code, notes, and snippets.

@insideone
Last active August 27, 2016 10:57
Show Gist options
  • Save insideone/ad5c0d66ae397ec3c60f926c4b7508ba to your computer and use it in GitHub Desktop.
Save insideone/ad5c0d66ae397ec3c60f926c4b7508ba to your computer and use it in GitHub Desktop.
PHP: получение файлов/папок рекурсивно
<?php
/**
* Возвращает массив всех директорий указанной директории рекурсивно
* @param string $dir Путь к директории
* @param string $filter Фильтр имени директории
* return array Массив путей к директориям
*/
function subdirs($dir, $filter = '*')
{
$dirs = glob(rtrim($dir, '/').'/'.$filter, GLOB_ONLYDIR);
$count = count($dirs);
for($i = 0; $i < $count; $i++)
{
$inner = glob($dirs[$i].'/'.$filter, GLOB_ONLYDIR);
$innerCnt = count($inner);
if ( $innerCnt === 0 ) continue;
array_splice($dirs, $i+1, 0, $inner);
$count += $innerCnt;
}
return $dirs;
}
<?php
/**
* Возвращает массив всех файлов указанной директории рекурсивно
* @param string $dir Путь к директории
* @param string $filter Фильтр имени файла
* return array Массив путей к файлам
*/
function subfiles($dir, $filter = '*')
{
$files = glob(rtrim($dir, '/').'/'.$filter);
$dirs = subdirs($dir);
foreach($dirs as $dirName)
{
$files = array_merge($files, glob($dirName.'/'.$filter));
}
$files = array_diff($files, $dirs);
return $files;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment