2010-03-27 50 views
1

我有这样的代码到目前为止它完美,但依赖于有被替代的目录:检查目录是否存在,如果它不选择一个图像

$path = '/home/sites/therealbeercompany.co.uk/public_html/public/themes/trbc/images/backgrounds/'.$this->slug; 
$bgimagearray = array(); 
$iterator = new DirectoryIterator($path); 
foreach ($iterator as $fileinfo) { 
    if ($fileinfo->isFile() && !preg_match('\.jpg$/', $fileinfo->getFilename())) { 
     $bgimagearray[] = "'" . $fileinfo->getFilename() . "'"; 
    } 
} 

我需要在顶部,所以在有些工作如果目录不存在,它默认为位于后台目录根目录的图像...

任何帮助,将不胜感激。

回答

2

你想要is_dir。测试你的slug目录,如果它不存在,请改用根目录。

+0

谢谢你的帮助 – Andy 2010-03-27 16:42:25

+0

is_dir在什么都没有的情况下工作吗? – Powertieke 2010-03-27 16:49:38

0

您也可以使用file_exists函数来检查目录。看到

+0

是的,但它会提供一个假阳性,如果有一个同名的文件存在 – Powertieke 2010-03-27 17:11:14

0

使用is_dir如果Dir是存在的,如果不是,设置$路径到当前路径(其中脚本运行)

if (!is_dir($path)) { 
    $path = $_SERVER["PATH_TRANSLATED"]; 
} 

我非常危险的假设$路径不要在其他地方使用:)

(is_dir是更好的,谢谢!)

+0

感谢您的信息! – Andy 2010-03-27 16:49:32

0

DirectoryIterator将抛出UnexpectedValueException当路径无法打开,所以你可以用该呼叫转变为try/catch块,然后回退到日e根路径。在功能:

function getBackgroundImages($path, $rootPath = NULL) 
{ 
    $bgImages = array(); 
    try { 
     $iterator = new DirectoryIterator($path); 
     // foreach code 
    } catch(UnexpectedValueException $e) { 
     if($rootPath === NULL) {     
      throw $e; 
     } 
     $bgImages = getBackgroundImages($rootPath); 
    } 
    return $bgImages; 
} 

当然file_existsis_dir的,但一个有效的选项了。

相关问题