到目前为止我有这个代码,完全可以依赖于有一个目录:
$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() . "'";
}
}
我需要在顶部工作,以便如果目录不存在,则默认为位于后台目录根目录中的图像......
任何帮助将不胜感激。
答案 0 :(得分:2)
你想要is_dir。测试你的slug目录,如果它不存在,请使用root后台目录。
答案 1 :(得分:0)
您还可以使用file_exists功能检查目录。
答案 2 :(得分:0)
使用is_dir查看dir是否存在,如果没有,则将$ path设置为当前路径(运行脚本的位置)
if (!is_dir($path)) {
$path = $_SERVER["PATH_TRANSLATED"];
}
我非常危险地认为$ path不会在其他任何地方使用:)
(is_dir更好,谢谢!)
答案 3 :(得分:0)
DirectoryIterator
将抛出UnexpectedValueException
,因此您可以将调用包装到try/catch
块中,然后回退到根路径。在一个函数中:
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_exists
或is_dir
也是有效选项。