mkdir
(PHP 4, PHP 5, PHP 7, PHP
mkdir — Makes directory
Description
Parameters
directory
-
The directory path.
Tip
A URL can be used as a
filename with this function if the fopen wrappers have been enabled.
See fopen() for more details on how to specify the
filename. See the Supported Protocols and Wrappers for links to information
about what abilities the various wrappers have, notes on their usage,
and information on any predefined variables they may
provide. permissions
-
The permissions are 0777 by default, which means the widest possible
access. For more information on permissions, read the details
on the chmod() page.Note:
permissions
is ignored on Windows.Note that you probably want to specify the
permissions
as an octal number,
which means it should have a leading zero. Thepermissions
is also modified
by the current umask, which you can change using
umask(). recursive
-
If
true
, then any parent directories to thedirectory
specified will
also be created, with the same permissions. context
-
A context stream
resource.
Return Values
Returns true
on success or false
on failure.
Note:
If the directory to be created already exists, that is considered an error
andfalse
will still be returned. Use is_dir() or
file_exists() to check if the directory already exists
before trying to create it.
Errors/Exceptions
Emits an E_WARNING
level error if the directory
already exists.
Emits an E_WARNING
level error if the relevant
permissions prevent creating the directory.
Examples
Example #1 mkdir() example
<?php
mkdir("/path/to/my/dir", 0700);
?>
Example #2 mkdir() using the recursive
parameter
<?php
// Desired directory structure
$structure = './depth1/depth2/depth3/';// To create the nested structure, the $recursive parameter
// to mkdir() must be specified.if (!mkdir($structure, 0777, true)) {
die('Failed to create directories...');
}// ...
?>
See Also
- is_dir() — Tells whether the filename is a directory
- rmdir() — Removes directory
- umask() — Changes the current umask
Found A Problem?
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);
?>
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);
?>
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!
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).
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
Last Updated :
01 Jun, 2018
The mkdir() creates a new directory with the specified pathname. The path and mode are sent as parameters to the mkdir() function and it returns TRUE on success or FALSE on failure.
The mode parameter in mkdir() function is ignored on Windows platforms.
Syntax:
mkdir(path, mode, recursive, context)
Parameters Used:
The mkdir() function in PHP accepts four parameters.
- path : It is a mandatory parameter which specifies the path.
- mode : It is an optional parameter which specifies permission.
The mode parameter consists of four numbers:- The first number is always zero.
- The second number specifies permissions for the owner.
- The third number specifies permissions for the owner’s user group.
- The fourth number specifies permissions for everybody else.
The set of possible values are :
- 1 = execute permissions
- 2 = write permissions
- 4 = read permissions
Multiple permissions can be set by adding up the following numbers.
- recursive: It is an optional parameter which can be used to set recursive mode.
- context : It is an optional parameter which specifies the behavior of the stream.
Return Value:
It returns TRUE on success or FALSE on failure.
Errors And Exception:
- Mode parameter in the mkdir() function must be specified in octal representation making it lead with a zero.
- An E_WARNING level error is generated if the directory already exists.
- An E_WARNING level error is generated if the relevant permissions prevent creating the directory.
Examples:
Input : mkdir("/documents/gfg/articles/"); Output : 1 Input : mkdir("/documents/gfg/articles/", 0770) Output : 1 Input : $nest = './node1/node2/node3/'; if (!mkdir($nest, 0777, true)) { echo('Folders cannot be created recursively'); } else { echo('Folders created recursively'); } Output : Folders created recursively
Below programs illustrate the mkdir() function.
Program 1
<?php
mkdir
(
"/documents/gfg/articles/"
);
?>
Output:
1
Program 2
<?php
mkdir
(
"/documents/gfg/articles/"
, 0770)
?>
Output:
1
Program 3
<?php
$nest
=
'./node1/node2/node3/'
;
if
(!
mkdir
(
$nest
, 0777, true))
{
echo
(
'Folders cannot be created recursively'
);
}
else
{
echo
(
'Folders created recursively'
);
}
?>
Output:
Folders created recursively
Related Article: PHP | rmdir( ) Function
Reference:
http://php.net/manual/en/function.mkdir.php
This guide will show you how it is possible to create a directory in PHP by using the mkdir function.
The mkdir function in PHP is a simple yet powerful function that allows you to create a directory wherever the running agent has permission.
At its most straightforward usage, you can create a single directory in the specified path. However, you can even use this function to create a whole directory tree by enabling its “recursive
” functionality.
It is a core part of PHP and is helpful for various cases where you need to create folders on the fly. For example, you might want to create directories based on the current date when handling uploads within PHP.
You may be interested in what each of these parameters does, so let us quickly go over them. We will show you a fair chunk of these in the later sections.
Definition of the mkdir Function in PHP
Before we proceed further, we should first touch on how the mkdir function is defined in PHP.
Below you can see how exactly the mkdir function is defined within PHP. It sports four parameters, but only the first one is required to utilize its functionality.
This function will return true
, if the directory was successfully created and false
if it failed.
Copy
You may be interested in what each of these parameters does, so let us quickly go over them. We will give examples of how each parameter is used later in this guide.
The Directory Parameter
The “directory
” parameter is required and is used to specify the directory path that you want to be created by this function.
The mkdir function in PHP has full support for both relative (./newdir/
) and absolute paths (/var/www/php/newdir
).
However, it is best to use absolute paths here as the current working directory might not be what you think.
If you want to create a directory relative to the current PHP file, you will want to append your directory with “__DIR__
“. This constant contains the current work directory.
For example, using the relative path example before, we would write “__DIR__ . '/newdir/'
“.
The mode Parameter
Using the “mode
” parameter, you can set the permissions that should be assigned to the folder when it is created.
By default, PHP will create the directory with the permissions “0777
” the widest possible access. The owner, group, and everyone else will have full access to this directory.
The mode value should typically be defined as an octal, meaning you should use the following format.
- The first number must always be a 0.
- The second number specifies the permissions for the owner.
- The third number sets the permission for the group that owns the directory.
- Finally, the fourth number sets the permissions for anyone else.
The value for each of these permission groups is calculated by adding the following numbers.
- 1 = Execute Permissions
- 2 = Write Permission
- 4 = Read Permission
For example, if we wanted our group owner only to have read and write permissions, we would use “6
” for that group.
You can learn more about how Linux handles permissions by checking out our chmod command guide.
Please note that if you are on a Windows-based system, this option will not do anything.
The recursive Parameter
PHP’s mkdir function will only attempt to create the last segment in a path by default.
For example with the path “/var/www/example/
“, PHP will only create the ending “/example/
” directory. If the previous directories don’t exist, then the function will fail.
You can set the “recursive
” parameter to true
to get around this. When set to true
, PHP will run through each part of the path, creating them if they don’t exist already.
The context Parameter
The context parameter is optional and allows you to control the file handle that PHP’s mkdir function will utilize.
For most cases, you will not need to utilize this parameter. It is only useful when you need to control the file stream.
Basic Usage of the mkdir Function in PHP
Let us start with the most basic way to use the mkdir function within PHP.
The simplest way to use mkdir is to pass in the directory that you want to create. The function will assume that the default values should be used for all other options.
With the following example we will be creating the directory “/example/directory/
“.
Copy
As recursive is set to false by default, the “/example/
” part of this directory must already exist. Otherwise, mkdir will return false
, and fail to create the directory.
Likewise, as we aren’t setting the “mode
” parameter, the default permissions of “0777
” are set when this folder is created.
Setting Permissions on Folder Creation with mkdir on PHP
The mkdir function in PHP allows you to set the permissions on the folders that it creates by utilizing its mode option.
You will still need to specify the directory you want to create for the first parameter. For our example below, we use the directory “/example/directory/
“.
We can set the permissions to be assigned to this new folder with the second parameter. This needs to be an octal value.
- The first number must remain
0
as this value is an octal. - The second number is the user privileges. In our example below, we set this to
7
.Using 7 gives the user execute (
1
), write (2
), and read (4
) privileges. - With the third number, we set the permissions for the group that owns the file.
With our example, we will set this number to
5
. This gives the group execute (1
) and read (4
) permissions. - The last and fourth number allows you to set the permission for all other users.
Like with the group permission, we also set this to 5 for our example.
Copy
When this bit of PHP is executed, it will use the mkdir function to create the directory “/example/directory/
“, with the permission “0755
“.
Creating Parent Directories using PHP’s mkdir Function
The final parameter that we will be showing you how to use is the recursive one. This is one of the most useful functions of PHP’s mkdir function, as it allows you to create a whole directory branch in a single function call.
To use this, we must define the directory and mode first. We will be using “/example/full/directory/tree/
” for our directory, and for the mode, we will be using the default “0777
“.
Now all we need to do is set the third (recursive) parameter to true.
Copy
With “true
” passed into the recursive parameter, mkdir will ensure that each part of the directory is created.
Create a Folder if it Doesn’t Exist Using mkdir in PHP
While PHP’s mkdir function helps create a directory, it doesn’t perform any checks to see if that directory exists before firing.
When used on a directory that already exists, the mkdir function will throw a warning indicating that it already exists.
To avoid this warning from occurring within the code, we can utilize PHP’s “file_exists
” function. Using this function, we can check if the directory exists before proceeding.
Below we have a simple PHP if conditional statement using the file_exists()
function to check if the directory does not (!
) exist.
Only if the file file_exists
function returns false
will our mkdir
function call be ran and our directory, “/example/directory/tree/
” be created.
Copy
Conclusion
By the end of this tutorial, we hope that you now understand how the mkdir function works in PHP.
This function is helpful as it allows you to create directories within PHP. It even allows you to set permissions on the new folders and recursively create any directories in the provided path.
Of course, the user that PHP is running under will need permission to create folders, so make sure you have your permissions set correctly.
Please comment below if you have any questions about using the mkdir function.
Be sure to check out our many other PHP tutorials, and our other coding guides.
Пройдите тест, узнайте какой профессии подходите
Работать самостоятельно и не зависеть от других
Работать в команде и рассчитывать на помощь коллег
Организовывать и контролировать процесс работы
Введение в работу с директориями в PHP
Работа с директориями — важная часть программирования на PHP. Она позволяет создавать, удалять, перемещать и читать содержимое папок на сервере. В этой статье рассмотрим основные функции и методы, которые помогут вам эффективно управлять директориями в PHP. Понимание этих функций является ключевым для разработки веб-приложений, которые требуют работы с файловой системой.

Создание и удаление директорий
Создание директорий
Для создания директорий в PHP используется функция mkdir()
. Она принимает два основных аргумента: путь к создаваемой директории и права доступа. Эта функция позволяет создать как одиночные директории, так и вложенные структуры директорий.
Функция mkdir()
также может принимать третий аргумент — флаг recursive
, который позволяет создавать вложенные директории. Например, если вы хотите создать структуру директорий parent/child
, вы можете использовать этот флаг.
Удаление директорий
Для удаления директорий используется функция rmdir()
. Она удаляет только пустые директории. Если директория не пуста, сначала нужно удалить все её содержимое. Это важно учитывать, чтобы избежать ошибок при выполнении скрипта.
Если директория содержит файлы или поддиректории, вам нужно будет рекурсивно удалить все её содержимое перед вызовом rmdir()
. Это можно сделать с помощью пользовательской функции.
Чтение содержимого директорий
Функция scandir()
Для чтения содержимого директории используется функция scandir()
. Она возвращает массив, содержащий имена файлов и поддиректорий. Это простой и удобный способ получить список всех элементов в директории.
Функция scandir()
также позволяет фильтровать результаты, исключая специальные элементы, такие как .
и ..
. Это делает её удобной для большинства задач по чтению содержимого директорий.
Функция opendir()
, readdir()
и closedir()
Эти функции предоставляют более низкоуровневый способ чтения содержимого директории. Они позволяют открывать директорию, читать её содержимое по одному элементу и закрывать директорию после завершения работы.
Использование этих функций может быть полезно, если вам нужно более детально контролировать процесс чтения содержимого директории.
Перемещение и переименование директорий
Функция rename()
Функция rename()
используется для перемещения и переименования директорий. Она принимает два аргумента: текущее имя директории и новое имя. Эта функция также может использоваться для перемещения директорий в другое место на файловой системе.
Функция rename()
полезна для организации файловой структуры и управления содержимым серверов.
Практические примеры и советы
Пример: Создание и удаление вложенных директорий
Создание и удаление вложенных директорий может быть выполнено с использованием функции mkdir()
с флагом recursive
и рекурсивного удаления содержимого перед вызовом rmdir()
.
Этот пример показывает, как можно создать и удалить вложенные директории, обеспечивая правильную структуру и порядок выполнения операций.
Совет: Проверка прав доступа
Перед выполнением операций с директориями, убедитесь, что у вашего скрипта есть необходимые права доступа. Это поможет избежать ошибок и проблем с безопасностью. Проверка прав доступа может быть выполнена с помощью функции is_writable()
.
Проверка прав доступа важна для предотвращения ошибок и обеспечения безопасности вашего приложения.
Пример: Чтение содержимого и фильтрация файлов
Чтение содержимого директории и фильтрация файлов может быть выполнена с помощью функции scandir()
и простого условия для исключения специальных элементов.
Этот пример показывает, как можно легко получить список файлов в директории, исключая ненужные элементы.
Совет: Использование исключений
Используйте исключения для обработки ошибок при работе с файловой системой. Это поможет сделать ваш код более надежным и понятным. Вы можете использовать конструкцию try-catch
для обработки возможных ошибок.
Использование исключений позволяет более гибко и эффективно обрабатывать ошибки, делая ваш код более устойчивым к непредвиденным ситуациям.
Работа с директориями в PHP может показаться сложной, но с правильными инструментами и подходами вы сможете легко управлять файловой системой на вашем сервере. Надеемся, что эта статья помогла вам разобраться в основных функциях и методах работы с директориями в PHP. Важно помнить, что понимание этих функций является ключевым для разработки надежных и эффективных веб-приложений.
Читайте также
Welcome to this tutorial on creating directories in PHP! Whether you’re a beginner or an experienced coder, I hope you find this guide helpful. We’ll start with the basics and work our way up to more advanced topics. So, let’s dive right in!
The mkdir() Function
The mkdir()
function is one of the most important functions in PHP when it comes to working with directories. It allows you to create a new directory on your server. Here’s how you use it:
<?php
$directory = "new_directory";
if (!file_exists($directory)) {
mkdir($directory);
echo "Directory created successfully!";
} else {
echo "Directory already exists!";
}
?>
In this example, we first define a variable $directory
that holds the name of the directory we want to create. Then, we use the file_exists()
function to check if the directory already exists. If it doesn’t, we call mkdir()
to create the directory. Finally, we print a message to let the user know whether the directory was created successfully or not.
The chdir() Function
The chdir()
function allows you to change the current working directory in PHP. This is useful when you need to navigate between different directories within your script. Here’s how you use it:
<?php
$directory = "new_directory";
chdir($directory);
echo getcwd(); // This will print the current working directory
?>
In this example, we first set the $directory
variable to the name of the directory we want to change to. Then, we call chdir()
with the $directory
variable as an argument to change the current working directory. Finally, we use the getcwd()
function to print the current working directory, which should now be the directory we just changed to.
The getcwd() Function
The getcwd()
function returns the current working directory in PHP. It’s useful for checking where you are in the file system or for displaying the current directory path to the user. Here’s how you use it:
<?php
echo getcwd(); // This will print the current working directory
?>
In this simple example, we just call getcwd()
without any arguments and print the result, which will be the current working directory.
The rmdir() Function
The rmdir()
function allows you to remove a directory from your server. However, it’s important to note that this function can only remove empty directories. If you want to delete a directory and all its contents, you’ll need to use the rmdir()
function in combination with other functions like unlink()
or array_map()
. Here’s how you use it:
<?php
$directory = "new_directory";
if (file_exists($directory)) {
rmdir($directory);
echo "Directory removed successfully!";
} else {
echo "Directory does not exist!";
}
?>
In this example, we first check if the directory exists using file_exists()
. If it does, we call rmdir()
to remove the directory. Finally, we print a message to let the user know whether the directory was removed successfully or not.
That’s it for our introduction to creating directories in PHP! Remember, practice makes perfect, so try out these functions in your own scripts and see how they work. If you have any questions or need further clarification on any of these topics, feel free to ask. Happy coding!
Credits: Image by storyset