如何检查是否存在多个文件夹,如wordpress style

时间:2017-04-15 11:51:22

标签: php wordpress

我正在使用以下PHP代码:

if (!file_exists('../products'))
    {
        mkdir('../products', 0777, true);
        $target = "Main Not Present, ";
    }
else
    {
        if(file_exists('../products'))
            {
                $timezone = new DateTimeZone("Asia/Kolkata");
                $datetime = new DateTime();
                $datetime->setTimezone($timezone);

                $year = $datetime->format('Y');
                $month = $datetime->format('M');
                $day = $datetime->format('D');
                $timestamp = $datetime->format('Y-m-d H:i:s');

                if(!file_exists('../products/'.$year))
                    {
                        mkdir('../products/'.$year, 0777, true);
                        $target = $target."With year not present also, ";
                    }
                else
                    {
                        if(file_exists('../products/'.$year))
                            {
                                if(!file_exists('../products/'.$year."/".$month))
                                    {
                                        $target = $target."With not not present also";
                                    }
                            }
                    }
            }
    }

我正在使用像Wordpress这样的CMS技术创建一个电子商务网站,但我试图检查某些目录是否存在,如果他们不创建它们并继续。我的代码的问题是当遇到这段代码时是真的

if (!file_exists('../products'))
{
    mkdir('../products', 0777, true);
    $target = "Main Not Present, ";
}

它创建了目录并且数据存储在变量中,问题是它没有进一步处理并且在else语句中是否存在该products文件夹中的其他文件夹。

我想要实现的是

1。)检查产品文件夹,如果它不存在然后创建它是否存在然后继续进行,让我们更糟糕的是它不存在然后在这种情况下,如果我想创建该文件夹并使我代码工作进一步,但使用此代码它只满足第一个if条件,并且不进入else语句以进一步满足代码。

任何人都可以帮我吗?提前谢谢。

1 个答案:

答案 0 :(得分:0)

上面提供的代码太多而且很大,我使用递归方法实现了它。

//recursive function created here
function check_create($path)
  {
    if (is_dir($path)) return true;
    $prev_path = substr($path, 0, strrpos($path, '/', -2) + 1 );
    $return = check_create($prev_path);
    return ($return && is_writable($prev_path)) ? mkdir($path) : false;
  }

//call the recursive function to check and create if not exists
check_create("path/to/directory");