mkdir

(PHP 4, PHP 5, PHP 7, PHP 8)

mkdirСоздаёт директорию

Описание

mkdir(
    string $directory,
    int $permissions = 0777,
    bool $recursive = false,
    ?resource $context = null
): bool

Пытается создать директорию, заданную в directory.

Список параметров

directory

Путь к директории.

Подсказка

В эту функцию в качестве имени файла можно передавать URL-адреса, если была включена директива fopen wrappers. Подробнее о том, как указать имя файла, рассказано в описании функции fopen(). В разделе «Поддерживаемые протоколы и обёртки» также даны ссылки на информацию о способностях поддерживаемых обёрток, замечания по работе с ними и список предопределённых переменных, которые они дают.

permissions

По умолчанию принимает значение 0777, что означает самые широкие права. Больше информации о правах доступа можно узнать на странице руководства функции chmod().

Замечание:

Аргумент permissions игнорируется в Windows.

Обратите внимание, что аргумент permissions необходимо задавать в виде восьмеричного числа (первой цифрой должен быть ноль). На аргумент permissions также влияет текущее значение umask, которое можно изменить при помощи umask().

recursive

Если указано значение true, то все родительские каталоги для указанного параметра directory также будут созданы, с теми же разрешениями.

context

Ресурс (resource) с контекстом потока.

Возвращаемые значения

Возвращает true в случае успешного выполнения или false, если возникла ошибка.

Замечание:

Если создаваемый каталог уже существует, это считается ошибкой и будет возвращено значение false. Используйте функцию is_dir() или file_exists(), чтобы проверить, существует ли уже каталог, прежде чем пытаться его создать.

Ошибки

Выдаёт ошибку уровня E_WARNING, если директория уже существует.

Выдаёт ошибку уровня E_WARNING, если соответствующие права доступа блокируют создание директории.

Примеры

Пример #1 Пример использования функции mkdir()

<?php
mkdir
("/path/to/my/dir", 0700);
?>

Пример #2 Использование mkdir() с параметром recursive

<?php
// Желаемая структура папок
$structure = './depth1/depth2/depth3/';

// Для создания вложенной структуры необходимо указать параметр
// $recursive в mkdir().

if (!mkdir($structure, 0777, true)) {
die(
'Не удалось создать директории...');
}

// ...
?>

Смотрите также

  • is_dir() - Определяет, является ли имя файла директорией
  • rmdir() - Удаляет директорию
  • umask() - Изменяет текущую маску прав доступа для вновь созданных файлов и каталогов (umask)

add a note

User Contributed Notes 5 notes

up
37
jack dot sleight at gmail dot com
14 years ago
When using the recursive parameter bear in mind that if you're using chmod() after mkdir() to set the mode without it being modified by the value of uchar() you need to call chmod() on all created directories. ie:

<?php
mkdir
('/test1/test2', 0777, true);
chmod('/test1/test2', 0777);
?>

May result in "/test1/test2" having a mode of 0777 but "/test1" still having a mode of 0755 from the mkdir() call. You'd need to do:

<?php
mkdir
('/test1/test2', 0777, true);
chmod('/test1', 0777);
chmod('/test1/test2', 0777);
?>
up
3
chelidze dot givia at gmail dot com
8 months ago
When creating a file using mkdir() the default root will be the DocumentRoot (in XAMPP) itself.

C:\xampp\htdocs\project/includes/something.php

If you use mkdir("myfile") in something.php, instead of creating the folder in includes, php will create it in the project folder
up
19
aulbach at unter dot franken dot de
24 years ago
This is an annotation from Stig Bakken:

The mode on your directory is affected by your current umask. It will end
up having (<mkdir-mode> and (not <umask>)). If you want to create one
that is publicly readable, do something like this:

<?php
$oldumask
= umask(0);
mkdir('mydir', 0777); // or even 01777 so you get the sticky bit set
umask($oldumask);
?>
up
6
Protik Mukherjee
19 years ago
mkdir, file rw, permission related notes for Fedora 3////
If you are using Fedora 3 and are facing permission problems, better check if SElinux is enabled on ur system. It add an additional layer of security and as a result PHP cant write to the folder eventhough it has 777 permissions. It took me almost a week to deal with this!

If you are not sure google for SElinux or 'disabling SELinux' and it may be the cure! Best of luck!
up
3
julius - grantzau - c-o-m
13 years ago
Remember to use clearstatcache()

... when working with filesystem functions.

Otherwise, as an example, you can get an error creating a folder (using mkdir) just after deleting it (using rmdir).
To Top