PHP mkdir(): Create a Directory

The PHP mkdir() function is used when we need to create a new directory. For example:

<?php
   $dir = "Documents";
   $chk = mkdir($dir);
   if($chk)
      echo "<p>A new directory is created</p>";
   else
      echo "<p>Unable to create</p>";
?>

Before executing the above PHP code, here is a snapshot of the current directory:

php mkdir function

After executing the above PHP code or example, here is the output produced in the web browser:

php mkdir create new directory

And here is the new snapshot of the current directory after executing the above PHP code:

php mkdir example

PHP mkdir() Syntax

The syntax of the mkdir() function in PHP is:

mkdir(directory, permissions, recursive, context)

The first (directory) parameter is required, whereas all the other three parameters are optional.

Note: The directory parameter is used to specify the directory to create.

Note: The permissions parameter is used to specify permission. The default value is 0777.

Note: The recursive parameter is used when we need to allow the creation of nested directories. The default value is false.

Note: The context parameter is used to specify the context resource. The default value is null.

The mkdir("xyz") is the same as mkdir("xyz", 0777, false, null).

Advantages of the mkdir() function in PHP

Disadvantages of the mkdir() function in PHP

PHP Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!