Andy
Andy

Reputation: 3021

if folder exists with PHP

I'd love some help....i'm not sure where to start in creating a script that searches for a folder in a directory and if it doesnt exist then it will simply move up one level (not keep going up till it finds one)

I am using this code to get a list of images. But if this folder didn't exist i would want it to move up to its parent.

$iterator = new DirectoryIterator("/home/domain.co.uk/public_html/assets/images/bg-images/{last_segment}"); foreach ($iterator as $fileinfo) {
    if ($fileinfo->isFile() && !preg_match('/-c\.jpg$/', $fileinfo->getFilename())) {
        $bgimagearray[] = "'" . $fileinfo->getFilename() . "'";
    } }

Upvotes: 4

Views: 5171

Answers (3)

S. Albano
S. Albano

Reputation: 707

To test if a directory exists, use is_dir()

http://php.net/function.is-dir

To move up to the parent directory would be by chdir('..');

http://php.net/function.chdir

Upvotes: 1

Alex Pliutau
Alex Pliutau

Reputation: 21937

It works: file_exists($pathToDir)

Upvotes: 2

Stephane Gosselin
Stephane Gosselin

Reputation: 9148

Put your directory name in a variable.

$directory = "/home/domain.co.uk/public_html/assets/images/bg-images/{last_segment}";

// if directory does not exist, set it to directory above.
if(!is_dir($directory)){
  $directory = dirname($directory)  
}

$iterator = new DirectoryIterator($directory);

Upvotes: 3

Related Questions