First, we will introduce the mkdir () function.
Mkdir ($ path, 0777, true );
The first parameter is required. It indicates the path of the multi-level directory to be created;
The second parameter: sets the directory permission. The default value is 0777, which means the maximum possible access;
The third parameter: true indicates that multi-level directories can be created.
Mkdir ($ dir, $ mode); however, it can only create one directory at a time, that is, it cannot create multi-level directories at a time, as shown below
Mkdir ('A'); // only one aa directory can be created.
Mkdir ('AA/bb/CC'); // if the aa/bb directory exists, you can create a cc Directory. Otherwise, an error is returned. If you want to create multiple directories, see the following code.
Example code (supports creating a Chinese directory ):
| The code is as follows: |
Copy code |
|
<? Php
Header ("Content-type: text/html; charset = utf-8 ");
// Multi-level directory to be created
$ Path = "dai/php learning ";
// Check whether a directory exists. If yes, a prompt is displayed. If no directory exists, create a directory.
If (is_dir ($ path )){
Echo "Sorry! The Directory ". $ path." already exists! ";
} Else {
// The third parameter is "true", indicating that multi-level directories can be created. iconv prevents Chinese Directory garbled characters
$ Res = mkdir (iconv ("UTF-8", "GBK", $ path), 0777, true );
If ($ res ){
Echo "directory $ path created successfully ";
} Else {
Echo "directory $ path creation failed ";
}
}
?>
|
Let's look at an example of Recursive directory creation.
I have compiled two methods for recursively creating directories for your reference. Thank you!
| The code is as follows: |
Copy code |
|
<? Php
/*
* Mkdir ($ dir, $ mode)
* Recursive directory creation in 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;
}
}
}
?>
// Code application instance
$ Path = "abc/ff/ss /";
Mkdirs ($ path, $ mode = 0777 ); |
This section describes how to recursively create directories and multi-level directories in php.