How to use the PHP function to create a directory?

In PHP, you can use the mkdir() function to create a directory. The syntax of this function is as follows:

Create a new directory.

Explanation of parameters:

  1. $pathname: The path of the directory to be created.
  2. $mode: Optional parameter that specifies the permission for the directory, default is 0777.
  3. $recursive: an optional parameter that specifies whether to recursively create directories, defaulting to false. If set to true, it will recursively create any missing parent directories.
  4. $context: Optional parameter to specify the context of the directory, default is null.

The code example is shown below:

<?php
$dir = "/path/to/directory";

// 创建目录
if (!file_exists($dir)) {
    if (mkdir($dir, 0777, true)) {
        echo "目录创建成功!";
    } else {
        echo "目录创建失败!";
    }
} else {
    echo "目录已存在!";
}
?>

In the code above, the first step is to define the directory path to be created. Then an if statement is used to check if the directory already exists. If it doesn’t exist, the mkdir() function is called to create the directory. If the creation is successful, the message “Directory created successfully!” is output, otherwise “Failed to create directory!” is output. If the directory already exists, it simply outputs “Directory already exists!”.

Make sure that the parent directory exists and has write permissions when creating a directory, otherwise you may encounter insufficient permission errors.

bannerAds