How to Create a Directory in PHP Using mkdir()
This article provides a quick and practical guide on how to use PHP’s
native mkdir() function to create new directories. You will
learn the basic syntax, how to configure file permissions, how to create
nested directories recursively, and how to implement best practices to
prevent errors when a directory already exists.
The Basic Syntax of mkdir()
The mkdir() function in PHP attempts to create the
directory specified by the path. The basic syntax is as follows:
bool mkdir(string $directory, int $permissions = 0777, bool $recursive = false, ?resource $context = null)$directory: The path to the directory you want to create.$permissions: The access permissions for the directory (defaults to0777, which means widest possible access). This parameter must be written as an octal number (starting with a leading zero).$recursive: If set totrue, PHP will automatically create any parent directories in the path that do not already exist.$context: An optional stream context resource.
The function returns true on success, or
false on failure.
Creating a Simple Directory
To create a single folder in the current directory, pass the directory name to the function:
<?php
$directoryName = "uploads";
if (mkdir($directoryName)) {
echo "Directory created successfully.";
} else {
echo "Failed to create directory.";
}
?>Best Practice: Checking if the Directory Already Exists
If you attempt to create a directory that already exists, PHP will
trigger an E_WARNING error. To prevent this, always check
if the folder exists using is_dir() or
file_exists() before calling mkdir():
<?php
$directoryName = "uploads";
if (!is_dir($directoryName)) {
if (mkdir($directoryName, 0755)) {
echo "Directory created successfully.";
} else {
echo "Failed to create directory.";
}
} else {
echo "Directory already exists.";
}
?>Note: In the example above, 0755 is used for
permissions, which is a standard choice for secure directories (owner
can write, everyone else can only read and execute).
Creating Nested Directories Recursively
If you want to create a path like uploads/images/2026/
where the intermediate folders (images and
2026) do not yet exist, you must set the third parameter
$recursive to true:
<?php
$nestedDirectory = "uploads/images/2026";
if (!is_dir($nestedDirectory)) {
// Setting the recursive parameter to true
if (mkdir($nestedDirectory, 0755, true)) {
echo "Nested directories created successfully.";
} else {
echo "Failed to create nested directories.";
}
}
?>