PHP Function Reference

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:
  • The first number is always zero (octal value)
  • The second number specifies permissions for the OWNER
  • The third number specifies permissions for the OWNER's USER GROUP
  • The fourth number specifies permissions for EVERYBODY ELSE
Possible values (to set multiple permissions, add up the following numbers):
  • 1 = execute permissions
  • 2 = write permissions
  • 4 = read permissions
Default is 0777.
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