PHP mkdir with recursive creation
Create a nested directory tree and verify the final directory.
A simple example
mkdir with recursive creation
- Start with An empty practice folder
- Do this Create a/b including parents
- Result Both directories exist
Syntax
mkdir($week, 0700, true)
Run these examples in PHP
Save one example at a time as lesson.php. Use PHP 8.2 or later.
php lesson.phpPrepare nested hand-in folders
A department creates a hand-in folder for each class and week. The job runs again if the first delivery is interrupted, so existing directories should remain usable on a second run.
<?php
$base = sys_get_temp_dir() . DIRECTORY_SEPARATOR . bin2hex(random_bytes(12));
if (!mkdir($base, 0700)) throw new RuntimeException("Cannot create workspace");
try {
$week = $base . '/class/week1';
for ($attempt = 0; $attempt < 2; $attempt++) {
if (!is_dir($week) && !mkdir($week, 0700, true) && !is_dir($week)) {
throw new RuntimeException('Cannot prepare hand-in folder');
}
}
echo "ready", PHP_EOL;
} finally {
foreach (['class/week1', 'class'] as $name) {
$path = $base . '/' . $name;
if (is_link($path) || is_file($path)) unlink($path);
elseif (is_dir($path)) rmdir($path);
}
rmdir($base);
}
ready
The second attempt finds the same directory and the application can use it.
Locate a rehearsal score
The choir stores each score inside a season folder. Create the named season or class folder and its proofs subfolder in an empty workspace. What state should the operator see after successful creation?
Locate a workshop handout
An instructor stores the current template in a class folder. Create the named season or class folder and its proofs subfolder in an empty workspace. What state should the operator see after successful creation?
What to watch for
Handle a regular file occupying any required directory name as an error.