tags:

views:

98

answers:

4

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 the images sat in the root of the background directory...

Any help would be appreciated.

+2  A: 

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

rjh
Thank you for your help
Andy
Does is_dir work when there is nothing there?
Powertieke
A: 

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

Neil Aitken
Yes, but it would provide a false positive if there were to be a file with the same name present
Powertieke
A: 

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!)

Powertieke
Thanks for this info!
Andy
A: 

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.

Gordon