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 t开发者_如何学运维he 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;
}
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 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.
精彩评论