📅  最后修改于: 2023-12-03 15:33:30.227000             🧑  作者: Mango
In PHP, mkdir()
function is used to create a directory. When creating a directory, sometimes we need to create the entire directory path recursively, i.e., if a directory is to be created inside a directory that doesn't exist, the entire directory path needs to be created. In such a case, we use mkdir()
function with the recursive flag.
bool mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive = FALSE [, resource $context ]]] )
The fourth parameter, $recursive
, if set to TRUE
, creates the entire directory path recursively.
Suppose we want to create a directory path /var/www/html/mywebsite/images
, where mywebsite
and images
directories do not exist. We can create this directory path recursively using the following code snippet:
<?php
$path = '/var/www/html/mywebsite/images';
// Create directory path recursively
if(!is_dir($path)) {
mkdir($path, 0777, true);
}
?>
In the above code, we first check if the directory path already exists using the is_dir()
function. If it doesn't exist, we call the mkdir()
function with the recursive flag set to true to create the entire directory path recursively.
$mode
sets the permissions for the newly created directory. In the above example, we set it to 0777
, which gives full permissions to the directory. It is recommended to set the permissions according to your needs and security requirements.$recursive
flag is set to TRUE, and any intermediate directory doesn't exist, mkdir()
function creates the intermediate directory with the permissions set to $mode
.