If the folder exists with PHP

I would really like it ... I don’t know where to start creating a script that looks for a folder in the directory, and if it does not exist, it will simply move one level (do not keep going until you find one)

I use this code to get a list of images. But if this folder does not exist, I would like it to move 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() . "'";
    } }
+3
source share
3 answers

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);
+2
source

Works: file_exists($pathToDir)

+1
source

To check if a directory exists, use is_dir ()

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

To navigate to the parent directory, do chdir ('..');

http://php.net/function.chdir

0
source

All Articles