PHP 8.5.0 Alpha 1 available for testing

mkdir

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

mkdirCrea un directorio

Descripción

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

Intenta crear el directorio especificado por directory.

Parámetros

directory

La ruta del directorio.

Sugerencia

Puede utilizar una URL como nombre de archivo con esta función, si el gestor fopen ha sido activado. Véase fopen() para más detalles sobre cómo especificar el nombre del archivo. Consulte Protocolos y Envolturas soportados para más información sobre las capacidades de los diferentes gestores, las notas sobre su uso, así como la información sobre las variables predefinidas que proporcionan.

permissions

El modo predeterminado es 0777, lo que significa el acceso más amplio posible. Para más información sobre los modos, lea los detalles en la página de chmod().

Nota:

permissions es ignorado en Windows.

Observe que probablemente se quiera especificar el modo como un número octal, lo que significa que debería de haber un cero inicial. El modo es modificado también por la actual máscara de usuario, la cual se puede cambiar usando umask().

recursive

Si el valor es true, entonces cualquier directorio padre del directorio especificado en el parámetro directory también será creado, con los mismos permisos.

context

Nota: Un resource de contexto de flujo.

Valores devueltos

Esta función retorna true en caso de éxito o false si ocurre un error.

Nota:

Si el directorio a crear ya existe, se considerará un error y se devolverá false. Utilice is_dir() o file_exists() para comprobar si el directorio ya existe antes de intentar crearlo.

Errores/Excepciones

Emite un error de nivel E_WARNING si el directorio ya existe.

Emite un error de nivel E_WARNING si los permisos relevantes impiden crear el directorio.

Ejemplos

Ejemplo #1 Ejemplo de mkdir()

<?php
mkdir
("/ruta/a/mi/directorio", 0700);
?>

Ejemplo #2 mkdir() usando el parámetro recursive

<?php
// Estructura de la carpeta deseada
$estructura = './nivel1/nivel2/nivel3/';

// Para crear una estructura anidada se debe especificar
// el parámetro $recursive en mkdir().

if(!mkdir($estructura, 0777, true)) {
die(
'Fallo al crear las carpetas...');
}

// ...
?>

Ver también

  • is_dir() - Indica si el fichero es un directorio
  • rmdir() - Elimina un directorio
  • umask() - Cambia el "umask" actual

add a note

User Contributed Notes 5 notes

up
32
jack dot sleight at gmail dot com
15 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
19
aulbach at unter dot franken dot de
25 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
8
julius - grantzau - c-o-m
14 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).
up
6
Protik Mukherjee
20 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
-2
chelidze dot givia at gmail dot com
1 year 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
To Top