PHP mkdir() Function: Syntax, Parameters, Return Values, and Usage Examples
This article explains the PHP mkdir() function, detailing its signature, parameter meanings, default mode, recursive option, return values, and provides two practical code examples demonstrating simple directory creation and nested directory creation with error handling.
mkdir() creates a new directory specified by $pathname with optional mode, recursive creation, and context parameters.
Signature: bool mkdir(string $pathname, int $mode = 0777, bool $recursive = false, resource $context)
Parameters:
pathname : The path of the directory to create.
mode : Permissions for the new directory (default 0777, representing the most permissive access).
recursive : When true, allows creation of nested directories specified in the pathname.
context : Optional stream context resource.
Return value: Returns TRUE on success, or FALSE on failure.
Example 1 – Simple directory creation:
<?php
mkdir("/path/to/my/dir", 0700);
?>Example 2 – Creating nested directories with error handling:
<?php
$structure = './depth1/depth2/depth3/';
if (!mkdir($structure, 0, true)) {
die('Failed to create folders...');
}
?>These examples illustrate how to use mkdir() for both single-level and multi-level directory creation in PHP scripts.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
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.