如何递归使用 PHP mkdir 函数来跳过现有目录并创建新目录


How to use PHP mkdir function recursively to skip existing directory and to create new one?

如何递归使用 PHP mkdir 函数来跳过现有目录并从string $pathname创建新目录

// works fine if directories don't exist
mkdir($root_dir . '/demo/test/one', 0775, true);
// It will throw error - Message: mkdir(): File exists
mkdir($root_dir . '/demo/test/two', 0775, true);

解决方案是什么?

您的代码应该按原样工作,当您/如果您按照 @chris85 的建议第二次运行它时,就会出现问题,您可以事先检查它们是否存在。

<?php
// given
$root_dir = __DIR__;
// and you want to have these
$dirs = [
    $root_dir . '/demo/test/one',
    $root_dir . '/demo/test/tow',
    $root_dir . '/demo/test/three',
    $root_dir . '/demo/test/four',
    $root_dir . '/demo/test/and/so/on',
];
// just check if they're not exists and then create them
foreach ($dirs as $dir) {
    if (!is_dir($dir)) {
        mkdir($dir, 0775, true);
    }
}

is_dir检查目录是否已存在:

if(!is_dir($pathname)) { 
   mkdir($pathname, 0775, true);
}