简体   繁体   中英

Bulletproof method for listing folders in a specific directory (PHP 4 compatible)

I have a need for a simple function that lists all folders (non-recursive) in a given directory. The directory will always be the same (the images folder of my theme directory).

I've been using the function below, but it fails when the PHP version is < 5.

I suppose I could wrap the function in a PHP version check. I'm just trying to make the function as bulletproof as possible while at the same time efficient.

Since it has such light duty, I'm thinking that requiring PHP 5 is overkill for this function

This function parses the theme's images directory and returns an array of all folders it finds there. That's really all it needs to do (which is why I'm thinking that using DirectoryIterator is overkill since it requires PHP5+). Also, the function_exists test does not work...

    function get_dirs($path = '.') 
    {
        $dirs = array();
        if(function_exists('DirectoryIterator'))
        {
            foreach (new DirectoryIterator($path) as $file) 
            {
                if ($file->isDir() && !$file->isDot()) 
                {
                $dirs[] = $file->getFilename();
                }
            }
        } 
        else
        {
            //exception
            return array("theme1" => "theme1", "theme2" => "theme2", "theme3" => "theme3");
        }
    return $dirs;
    }

The dir directory class has been available since PHP 4, so should be ideal for your purposes.

There are some good examples on the manual page itself, so I won't duplicate them here.

PHP/4.0 or greater:

<?php

$dh = opendir('/');
if($dh){
    while(($item = readdir($dh)) !== false){
        if( is_dir($dir . $item) ){
            echo $item . "\n";
        }
    }
    closedir($dh);
}

?>

PHP/4.3 or greater:

<?php

foreach(glob('/*', GLOB_ONLYDIR) as $i){
    echo $i . "\n";
}

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM