SoFunction
Updated on 2025-03-10

PHP method to create multi-level directories using mkdir

This article describes how PHP uses mkdir to create multi-level directories. Share it for your reference, as follows:

In PHP, you can create multi-level directories by using mkdir(). Compared to the previous one-level creation, this function is very useful.

The following is the introduction of the functions in the php manual:

Copy the codeThe code is as follows:
bool mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive = false [, resource $context ]]] )

The return value is bool type.

The first parameter: Must represent the path to the multi-level directory to be created;

The second parameter: set the permissions of the directory, the default is 0777, which means the maximum possible access;

The third parameter: true means that multi-level directories are allowed to be created.

Note: You can create Chinese directories

Copy the codeThe code is as follows:
mkdir(iconv("utf-8", "gbk", $path),0777,true);
Need to use iconv to transcode

The complete example code is as follows:

<?php
  header("Content-type:text/html;charset=utf-8");
  //The multi-level directory to be created  $path="dai/php/php learning";
  //Judge whether the directory exists or not, give a prompt, if it does not exist, create a directory  if (is_dir($path)){ 
    echo "Sorry! Directory" . $path . "Already exists!";
  }else{
    //The third parameter is "true" to indicate that multi-level directories can be created, iconv prevents Chinese directories from being garbled.    $res=mkdir(iconv("UTF-8", "GBK", $path),0777,true); 
    if ($res){
      echo "Directory $path created successfully";
    }else{
      echo "Creation of directory $path failed";
    }
  }
?>

I hope this article will be helpful to everyone's PHP programming.