258 of 410 menu

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

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

Example

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

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

Example

Let's create a directory specifying 0755 access permissions:

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

Example

Let's create nested directories using the recursive flag:

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

Example

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

<?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
byenru