Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if folder exists with PHP

Tags:

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() . "'";
    } }
like image 307
Andy Avatar asked Oct 20 '25 02:10

Andy


1 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);
like image 50
Stephane Gosselin Avatar answered Oct 22 '25 17:10

Stephane Gosselin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!