【问题标题】:how to check whether multiple folders exists or not like wordpress style如何检查是否存在多个文件夹,如 wordpress 样式
【发布时间】:2017-04-15 11:51:21
【问题描述】:

我正在使用以下 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";
                                    }
                            }
                    }
            }
    }

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

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

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

我想要实现的是

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

谁能帮我解决这个问题?提前致谢。

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    上面提供的代码bug太大,我用递归的方法实现的。

    //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");
    

    【讨论】:

      猜你喜欢
      • 2013-03-12
      • 1970-01-01
      • 2011-11-15
      • 2011-02-21
      • 2013-08-24
      • 1970-01-01
      • 1970-01-01
      • 2010-12-10
      • 1970-01-01
      相关资源
      最近更新 更多