PHP mkdir() Function
The PHP mkdir() function attempts to create the specified directory.
Syntax
mkdir(directory, permissions, recursive, context)
Parameters
directory |
Required. Specify the path to the directory to be created. |
permissions |
Optional. Specify the new permissions, given as an octal value (starting with 0). The parameter consists of four numbers:
|
recursive |
Optional. If set to true it allows the creation of nested directories specified by directory. Default is false. |
context |
Optional. Specify the context of the file handle. Context is a set of options that can modify the behavior of a stream. |
Return Value
Returns true on success or false on failure.
Exceptions
If the directory already exists or the relevant permissions prevent creating the directory, an E_WARNING level error is thrown.
Example:
In the example below, mkdir() function is used to create the specified directory.
<?php $dir = "temp"; //creating a folder in the current directory if(mkdir($dir)) { echo "$dir directory is successfully created.\n"; } else { echo "Can not create $dir directory.\n"; } if(rmdir($dir)) { echo "$dir directory is successfully deleted.\n"; } else { echo "Can not delete $dir directory.\n"; } ?>
The output of the above code will be:
temp directory is successfully created. temp directory is successfully deleted.
Example: using recursive parameter
By using recursive parameter a nested directory structure can be created. Consider the example below:
<?php $dir = "./temp1/temp2/temp2"; //creating a nested directory structure //in the current directory if(mkdir($dir, 0777, true)) { echo "$dir directory is successfully created.\n"; } else { echo "Can not create $dir directory.\n"; } ?>
The output of the above code will be:
./temp1/temp2/temp2 directory is successfully created.
❮ PHP Filesystem Reference