Home >Backend Development >PHP Tutorial >The mkdir function in PHP creates directories (folders) recursively_PHP tutorial
In PHP, the mkdir function creates a directory. It cannot create a directory recursively. We need to traverse the directory and then call mkdir. Let’s take a look at the operation method.
Example
The code is as follows | Copy code | ||||
* Makes directory and returns BOOL(TRUE) if exists OR made. * * @param $path Path name * @return bool */ function rmkdir($path, $mode = 0755) { $path = rtrim(preg_replace(array("/\/", "//{2,}/"), "/", $path), "/"); $e = explode("/", ltrim($path, "/")); If(substr($path, 0, 1) == "/") { $e[0] = "/".$e[0]; } $c = count($e); $cp = $e[0]; for($i = 1; $i < $c; $i++) { If(!is_dir($cp) && !@mkdir($cp, $mode)) { return false; } $cp .= "/".$e[$i]; } Return @mkdir($path, $mode); } ?>
|
Somehow the recursive version of mkdir didn't work for me on Mac and the workaraounds listed
代码如下 | 复制代码 |
function mkdir_r($dirName, $rights=0777){ Tested and works ;) |
The code is as follows | Copy code |
function mkdir_r($dirName, $rights=0777){ $dirs = explode('/', $dirName); $dir=''; foreach ($dirs as $part) { $dir.=$part.'/'; If (!is_dir($dir) && strlen($dir)>0) mkdir($dir, $rights); } } ?> Tested and works ;) |
例3
代码如下
|
复制代码
|
||||
function mkdirs($dir) |
}