The mkdir Function

The mkdir function creates a new directory at the specified path. The first parameter of the function accepts a string with the path to the directory, the second (optional) - access permissions as an octal number, the third (optional) - a flag for recursive directory creation. By default, permissions are set to 0777 (maximum permissions).

Syntax

phpmkdir(path, [mode], [recursive], [context]);

Example

Let's create a directory 'test' in the current folder:

php<?php
  mkdir('test');
?>

Example

Let's create a directory specifying 0755 access permissions:

php<?php
  mkdir('test2', 0755);
?>

Example

Let's create nested directories using the recursive flag:

php<?php
  mkdir('test3/sub1/sub2', 0777, true);
?>

Example

Let's check if the directory exists before creating it:

php<?php
  $dir = 'new_dir';
  if (!file_exists($dir)) {
    mkdir($dir);
    echo 'directory created';
  } else {
    echo 'directory already exists';
  }
?>

See Also

  • the rmdir function,
    which deletes a directory
  • the is_dir function,
    which checks if a directory exists
  • the chmod function,
    which changes access permissions
  • the scandir function,
    which reads the contents of a directory