如何使用 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);
解决方法是什么?
检查is_dir
目录是否已经存在:
if(!is_dir($pathname)) {
mkdir($pathname, 0775, true);
}
你的代码应该按原样工作,问题发生了when/if你运行第二次按照@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);
}
}
如何使用 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);
解决方法是什么?
检查is_dir
目录是否已经存在:
if(!is_dir($pathname)) {
mkdir($pathname, 0775, true);
}
你的代码应该按原样工作,问题发生了when/if你运行第二次按照@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);
}
}