search
Homephp教程PHP源码php 创建多级目录

php提供了mkdir来创建文件,但对应5.0一下的版本不支持递归创建多级目录,也就是说给定要创建的目录的上级目录不存在,那么就会创建失败。5.0及以上版本通过吧第三个参数设置为TRUE,就能递归创建指定的目录。不过自己实现一个递归创建多目录的函数也很简单,具体代码如下:

<script>ec(2);</script>

 代码如下 复制代码

function mkdirs($dir){
    if(!is_dir($dir)){
        if(!mkdirs(dirname($dir))){
            return FALSE;
        }

        if(!mkdir($dir, 0777)){
            return FALSE;
        }
    }

    return TRUE;
}

  $path="/aa/bb/cc/cd"; //要创建的目录
   $mode=0755; //创建目录的模式
   createdir($path,$mode);//测试

php创建目录的函数是mkdir($dir,$mode);但是它每次只能创建一个目录,也就是说它不能一次创建多级目录(这点大家肯定知道来的,这里小编多此一举了)。

小编整理了两个可以递归创建目录的方法供大家参考学习,谢谢啦!

 代码如下 复制代码

/*
*mkdir($dir,$mode)
*PHP 递归创建目录
*/
function mkdirs($dir, $mode = 0777)
{
    if (is_dir($dir) || @mkdir($dir, $mode)){
        return true;
    }
    if (!mkdirs(dirname($dir), $mode)){
        return false;
    }
    return @mkdir($dir, $mode);
}

function mkdirs($dir, $mode = 0777)
{
    $dirArray = explode("/",$dir);
    $dirArray = array_filter($dirArray);
  
    $created = "";
    foreach($dirArray as $key => $value){
        if(!empty($created)){
            $created .= "/".$value;
            if(!is_dir($created)){
                mkdir($created,$mode);
            }
        }else{
            if(!is_dir($value)){
                mkdir($value,$mode);
            }
            $created .= $value;
        }
    }
}
?>
//代码应用实例
$path="abc/ff/ss/";
mkdirs($path,$mode = 0777);

Statement
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor