mkdir()
The mkdir() function is a built-in PHP function that creates a new directory. This function takes two parameters: the name of the directory to create and an
What is the mkdir() Function?
The mkdir() function is a built-in PHP function that creates a new directory on the file system. You reach for it whenever your script needs to make a folder at runtime — for example, to store uploaded files, generate per-user cache directories, or set up an export folder before writing reports into it.
This page covers the function's signature, each parameter (including the often-misunderstood permissions argument), how to create nested directories in one call, the return value and how to handle errors, and the common gotchas that trip people up.
Here's the basic syntax of the mkdir() function:
The PHP syntax of mkdir()
mkdir(string $directory, int $permissions = 0777, bool $recursive = false, ?resource $context = null): boolParameters
| Parameter | Description |
|---|---|
$directory | The path of the directory to create. Can be relative (resolved against the script's current working directory) or absolute. |
$permissions | An octal mode for the directory's permissions on Unix-like systems. Defaults to 0777 (the most permissive). Ignored on Windows. The note below explains why this is rarely the actual result. |
$recursive | When true, missing parent directories are created automatically. When false (default), mkdir() fails if any parent in the path doesn't already exist. |
$context | An optional stream context resource. Rarely needed for local file systems. |
A note on permissions and umask
The $permissions value you pass is not applied verbatim. The operating system subtracts the process umask from it. For example, with the common umask 022, calling mkdir($dir, 0777) produces a directory with mode 0755, not 0777. Because of this, always pass the mode you actually want and don't assume 0777 means "world-writable" — it usually doesn't.
For security, prefer 0755 (owner can read/write/execute, everyone else can read/execute) over the default 0777. If you need an exact mode regardless of umask, call chmod() after creating the directory.
How to Use the mkdir() Function?
Using the mkdir() function is straightforward. Here are the steps to follow:
- Specify the path of the directory you want to create.
- Call the
mkdir()function, passing in the directory path as the first parameter, an optional permissions mode as the second parameter, and a boolean flag as the third parameter to create parent directories if needed.
Here's an example code snippet that demonstrates how to use the mkdir() function:
How to Use the mkdir() Function?
<?php
$dir = '/path/to/new/directory';
// 0755 is recommended for security (owner: rwx, others: rx)
$permissions = 0755;
if (!is_dir($dir)) {
if (mkdir($dir, $permissions, true)) {
echo "Directory created successfully!";
} else {
echo "Failed to create directory.";
}
} else {
echo "Directory already exists!";
}In this example, we use is_dir() to check whether the target already exists. We specify a more secure permissions mode (0755) and pass true as the third argument to enable recursive creation. The mkdir() function returns a boolean value, so we wrap the call in an if statement to handle success or failure gracefully. If the directory doesn't exist, we attempt to create it and print a success or failure message. If it already exists, we print an existing message.
Creating nested directories
Without the recursive flag, mkdir() can only create the last segment of a path — every parent must already exist. Passing true as the third argument tells PHP to create the whole chain at once:
<?php
// Fails if "cache" or "cache/images" don't already exist:
// mkdir('cache/images/thumbs'); // Warning + returns false
// Works — creates cache, cache/images and cache/images/thumbs as needed:
if (mkdir('cache/images/thumbs', 0755, true)) {
echo 'Nested directories created.';
}Return value and handling errors
mkdir() returns true on success and false on failure. On failure it also raises an E_WARNING — for example when the parent directory is missing, the path already exists, or the process lacks write permission.
There are two clean ways to deal with that warning:
<?php
// 1. Guard with is_dir() so you never try to recreate an existing folder.
$dir = 'uploads';
if (!is_dir($dir) && !mkdir($dir, 0755, true) && !is_dir($dir)) {
// The second is_dir() guards against a race where another
// process created the directory between our two checks.
throw new RuntimeException("Directory \"$dir\" could not be created");
}
// 2. Suppress the warning with @ only if you immediately check the result.
if (!@mkdir($dir, 0755) && !is_dir($dir)) {
echo 'Could not create directory.';
}Avoid using @ on its own without checking the return value — silently swallowing the warning makes failures invisible.
Common gotchas
- The directory already exists.
mkdir()returnsfalseand warns. Always check withis_dir()first, or rely on the recursive-creation idiom above. - Permissions are filtered by umask. As covered above, the mode you pass is masked. Use
chmod()for an exact mode. - Relative paths depend on the working directory. A relative path is resolved against the script's current directory, which may differ from the file's location. Use an absolute path (e.g.
__DIR__ . '/uploads') when in doubt. - Windows ignores the permissions argument entirely — it's a no-op there.
Related functions
rmdir()— remove an empty directory (the counterpart tomkdir()).scandir()— list the contents of a directory.chmod()— change a directory's permissions after creation.fopen()— open or create a file once the directory exists.
Conclusion
The mkdir() function is a useful tool in PHP for creating new directories on a file system. The key things to remember are: pass an explicit, secure permission mode (such as 0755) rather than relying on the 0777 default, use the recursive flag when parent directories may be missing, and always check the boolean return value so failures don't go unnoticed. With those habits, mkdir() becomes a reliable building block for any script that works with the file system.