php: read directory
2019-12-29 00:00:00
IN1
,
2023-04-10 14:16:30
IN1
here are different ways to read a directory with php.
current level
using array_diff & scandir: read /var/www/Foo/
and ignore .dot files
$aContent = array_diff(scandir ('/var/www/Foo/'), array('..', '.', '.htaccess', '.htpasswd'));
using preg_grep & scandir: read /var/www/Foo/
$aContent = preg_grep('/^([^.])/', scandir('/var/www/Foo/'));
using 3 array* functions & scandir: read and ignore .dot files
/**
* @param string $sFilePath
* @return array
*/
function getDirContent($sFilePath)
{
$aContent = array_values(
array_map(
'trim',
array_diff(
scandir($sFilePath),
array('..', '.', '.htaccess', '.htpasswd')
)
)
);
return $aContent;
}
using glob: reading directories only beneath /var/www/Foo/
$aModule = glob('/var/www/Foo/*', GLOB_ONLYDIR);
recursive, with Filter
/**
* @param string $sFilePath
* @return string $sPattern
* @return RegexIterator $oRegexIterator
*/
function getRegexIterator($sDir = '.', $sPattern = '/\.php$/')
{
$oRegexIterator = new \RegexIterator(
new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($sDir)
),
$sPattern
);
return $oRegexIterator;
}
// Usage
$oRegexIterator = getRegexIterator(__DIR__, '/\.php$/');
foreach ($oRegexIterator as $oFile)
{
(false === $oFile->isFile()) ? continue : false;
echo $oFile->getPathname() . "\n";
}