Using PHP mkdir() to Create Directories: Syntax, Parameters, and Practical Examples
This article explains PHP's mkdir() function, detailing its syntax, parameters, return values, and providing practical examples for creating single directories, recursive directories, setting permissions, and using optional stream contexts, along with code snippets and explanations of each argument's effect.
In PHP development, creating directories is common. The built‑in mkdir() function provides this capability.
Basic Syntax of mkdir()
<code>mkdir(string $pathname, int $mode = 0777, bool $recursive = false, resource $context = null): bool</code>Parameter Description
$pathname : the directory path to create.
$mode : optional permission bits, default 0777.
$recursive : optional flag to create nested directories, default false.
$context : optional stream context, default null.
Return Value
Returns true on success, false on failure.
Creating a Single Directory
Example of creating a single directory:
<code><?php
$dir = './test';
if (mkdir($dir)) {
echo "Directory created successfully!";
} else {
echo "Directory creation failed!";
}
?></code>The script attempts to create ./test and outputs the result.
Recursive Directory Creation
To create multi‑level directories, set the third argument $recursive to true :
<code><?php
$dir = './test1/test2/test3';
if (mkdir($dir, 0777, true)) {
echo "Directory created successfully!";
} else {
echo "Directory creation failed!";
}
?></code>This creates the three‑level path test1/test2/test3 .
Setting Directory Permissions
The second argument $mode controls permissions. By default it is 0777 . To set a different mode, specify it, e.g., 0755 :
<code><?php
$dir = './test';
if (mkdir($dir, 0755)) {
echo "Directory created successfully!";
} else {
echo "Directory creation failed!";
}
?></code>Mode 0755 gives the owner read/write/execute and others read/execute.
Using the Context Parameter
The fourth argument $context is for stream contexts (e.g., FTP or HTTP). If not needed, set it to null :
<code><?php
$dir = './test';
if (mkdir($dir, 0777, false, null)) {
echo "Directory created successfully!";
} else {
echo "Directory creation failed!";
}
?></code>Summary
The article covered the basic usage of mkdir() , including creating single and recursive directories, adjusting permissions, and optional context usage, enabling developers to create directories efficiently in PHP projects.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.