php: read directory

2019-12-29 2019-12-30 07:26:47 PHP,directory,regex,array,EN

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";
}

This website uses Cookies to provide you with the best possible service. Please see our Privacy Policy for more information. Click the check box below to accept cookies. Then confirm with a click on "Save".