将DirectoryIterator()放入PHP中的for循环中时出错!

时间:2011-03-16 04:05:56

标签: php

这是我的代码,可以浏览其他驱动器中的所有特殊文件夹“folderContainer”:

$folderNames = '';
// go through all drives.Just want to find out which has folderContainer
for($i='D';$i<='Z';$i++){ 
     // get the path    
     $path = realpath($i.':\\folderContainer\\');

     $folders = new DirectoryIterator($path);

     foreach($folders as $folder){
         if($folder->isDot()) continue;
         // get folder's name which match my pattern
         if ($folder->isDir() && preg_match('/^[A-Z]{1}[0-9]{1,9}$/i', $folders)){
              // store the folder name
              $folderNames .= ' '.$folder.' ';
          }
     } 
} 

并收到以下错误消息:

Fatal error: Uncaught exception 'RuntimeException' with message 'Directory name must not be empty.' 

但是当我将$path设置为"D:\\folderContainer\\"而没有循环时,我的代码工作正常。那么,我该如何让代码遍历其他驱动器中的所有folderContainer

非常感谢!!

1 个答案:

答案 0 :(得分:1)

如果路径不存在,

realpath将返回null。也许你想跳过不存在的文件夹

//...
$path = realpath($i.':\\folderContainer\\');
if (empty($path))
    continue;
//...