开发者

Check directory exists and if it doesnt choose an image

开发者 https://www.devze.com 2022-12-24 03:44 出处:网络
I have this code so far which perfectly but relies on there being a directory in place: $path = \'/home/sites/therealbeercompany.co.uk/public_html/public/themes/trbc/images/backgrounds/\'.$this->s

I have this code so far which perfectly but relies on there being a directory in place:

    $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() . "'";
    }
}

I need to work in a bit at the top so that if the directory doesnt exist it defaults to th开发者_运维技巧e images sat in the root of the background directory...

Any help would be appreciated.


You want is_dir. Test your slug directory, and if it doesn't exist, use the root background directory instead.


Use is_dir to see if the dir is there, and if not, set $path to the current path (where the script is running from)

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

I very much dangerously assumed that $path is not going to be used anywhere else :)

(is_dir is better, thanks!)


DirectoryIterator will throw an UnexpectedValueException when the path cannot be opened, so you can wrap the call into a try/catch block and then fallback to the root path. In a function:

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;
}

But of course file_exists or is_dir are a valid options too.


You could also use the file_exists function to check for the directory.

0

精彩评论

暂无评论...
验证码 换一张
取 消