What is the mkdir() function in PHP?

Share

mkdir() is a built-in function in PHP.

The mkdir() function creates a new directory within the specified path with a specified mode that sets permissions for the directory.

The mkdir() function

Syntax

The following is the function prototype:

 mkdir(path, mode, recursive, context) 

Parameters and return value

The mkdir() function takes the following input parameters:

  • path: The path of the file that is created.

  • mode: Optional. A sequence of four numbers that specifies the permissions for the file. A breakdown of the four numbers is given below:

  1. The first number is always 0.
  2. The second number specifies owner permissions.
  3. The third number specifies the owner’s user group permissions.
  4. The fourth number specifies permissions for others.

The table below shows possible values for each number:

Value

Description

1

Execute permissions

2

Write permissions

4

Read permissions

Note: To set multiple permissions, we can add the above numbers. For example, 7 (1 + 2 + 4) specifies all permissions. The default mode is set to 0777.

  • recursive: Optional. Used to set recursive mode.

  • context: Optional. Specifies the contextbehavior of the stream of the filehandle.

The function returns TRUE on successful execution. Otherwise, the function returns FALSE.

Code

<?php
// Creating a simple directory. Default mode is 0777
echo mkdir("./Edpresso");
echo "\n";
// Creating directory in recursive mode with different permissions
echo mkdir ("./Edpresso/myDirectory", 0700, true);
?>

In the above example, we start by creating a new directory, Edpresso. An output of 1 shows that the function was executed successfully.

Then, we create a new directory within our first directory with the path ./Edpresso/myDirectory. This directory is created in recursive mode.

Copyright ©2024 Educative, Inc. All rights reserved