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.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP mkdir() Function: Syntax, Parameters, Return Values, and Usage Examples

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendFilesystemdirectoryphp-functionsmkdir
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.