Home > php教程 > php手册 > php中mkdir函数递归创建目录(文件夹)

php中mkdir函数递归创建目录(文件夹)

WBOY
Release: 2016-05-25 16:53:33
Original
1134 people have browsed it

在php中mkdir函数是创建目录它自身是不可以递归创建目录了,我们需要遍历进行目录然后调用mkdir即可,下面来看一下操作方法。

<?php
/**
 * 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);
}
?>
Copy after login

例2

Somehow the recursive version of mkdir didn't work for me on Mac and the workaraounds listed

below alsow didn't work for me, so heres my solution:

<?php
function mkdir_r($dirName, $rights = 0777) {
    $dirs = explode(&#39;/&#39;, $dirName);
    $dir = &#39;&#39;;
    foreach ($dirs as $part) {
        $dir.= $part . &#39;/&#39;;
        if (!is_dir($dir) && strlen($dir) > 0) mkdir($dir, $rights);
    }
}
?>
Copy after login

Tested and works ;)


例3

<?php
function mkdirs($dir) {
    if (!is_dir($dir)) {
        if (!mkdirs(dirname($dir))) {
            return false;
        }
        if (!mkdir($dir, 0777)) {
            return false;
        }
    }
    return true;
}
function rmdirs($dir) {
    $d = dir($dir);
    while (false !== ($child = $d->read())) {
        if ($child != &#39;.&#39; && $child != &#39;..&#39;) {
            if (is_dir($dir . &#39;/&#39; . $child)) rmdirs($dir . &#39;/&#39; . $child);
            else unlink($dir . &#39;/&#39; . $child);
        }
    }
    $d->close();
    rmdir($dir);
}
?>
Copy after login

三个创建目录的函数都有自己的优点,这里我也没有一个个测试了,只使用了第二个感觉非常的不错。


永久链接:

转载随意!带上文章地址吧。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template