Home  >  Article  >  Backend Development  >  PHP uses the mkdir() function to create multi-level directories

PHP uses the mkdir() function to create multi-level directories

angryTom
angryTomforward
2019-10-14 18:39:554146browse

The following introduces mkdir() in php to create multi-level directories.

1. Function description

bool mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive = false [, resource $context ]]] )

The first parameter $pathname: required, represents the path of the one-level or multi-level directory to be created;

The second parameter $mode: sets the permissions of the directory, the default is 0777, which means the maximum possible access rights;

The third parameter $recursive: true means that the creation of multi-level directories is allowed.

2. Return value

Returns TRUE on success, or FALSE on failure.

3. Classic examples

<?php
 
header("Content-type:text/html;charset=utf-8");
 
//要创建的多级目录
$path = "./whm/php/php学习";
 
// 判断目录存在否,存在给出提示,不存在则创建目录
// is_dir() - 判断给定文件名是否是一个目录
if (is_dir($path)){
    echo "对不起!目录 " . $path . " 已经存在!";
}else{
    // 第三个参数为true时表示能创建多级目录
    $res=mkdir($path, 0777, true);
    if ($res){
        echo "目录 $path 创建成功";
    }else{
        echo "目录 $path 创建失败";
    }
}

4. Error examples

I believe many beginners will create multi-level directories like this. In fact, it is wrong to create multi-level directories like this

mkdir(&#39;aa/bb/cc&#39;);//如果有aa/bb目录就可以成功创建cc目录否则会报错哦,如果要创建多目录我们看下面代码

5. Solution to the problem of no write permission after mkdir()

mkdir(&#39;文件地址&#39;, 0777); 
chmod(&#39;文件地址&#39;, 0777);
// 最后,需要注意一点,权限值最好使用八进制表示,即 0 开头,而且一定不要加引号。
//  原因:代码错误,&#39;0777&#39;不应使用字符串参数,而是使用0777值

For more PHP related knowledge, please visit PHP中文网!

The above is the detailed content of PHP uses the mkdir() function to create multi-level directories. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:www.whmblog.cn. If there is any infringement, please contact admin@php.cn delete