Skip to content
← Back to Snippets
Code

Create a Directory

Creates a relative directory beneath an approved base path, validates the directory name, and reports whether it was created or already existed.

Purpose

Creates a relative directory beneath an approved base path, validates the directory name, and reports whether it was created or already existed.

Snippet details

ContextFilesystemLevelProductionCopy-and-paste statusMarked safe after review.

Categories

  • Forms and Validation

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Create a Directory.
 *
 * Purpose:
 * Creates a directory under a known base path while rejecting absolute paths
 * and parent-directory traversal.
 *
 * @param string $base_directory Approved base directory.
 * @param string $relative_directory Relative directory path to create.
 * @return array Creation status and resolved target path.
 */
function ogSnippetCreateADirectory(string $base_directory, string $relative_directory): array {
	$base_real = realpath($base_directory);
	$relative_directory = trim($relative_directory);

	if ($base_real === false || is_dir($base_real) === false) {
		return array('success' => false, 'created' => false, 'path' => '', 'message' => 'Base directory is invalid.');
	}

	if ($relative_directory === '' || substr($relative_directory, 0, 1) === '/' || strpos($relative_directory, '..') !== false) {
		return array('success' => false, 'created' => false, 'path' => '', 'message' => 'Relative directory path is invalid.');
	}

	$relative_directory = str_replace('\\', '/', $relative_directory);
	$target_path = $base_real.DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $relative_directory);

	if (is_dir($target_path) === true) {
		return array('success' => true, 'created' => false, 'path' => $target_path, 'message' => 'Directory already exists.');
	}

	$created = mkdir($target_path, 0755, true);
	if ($created === false) {
		return array('success' => false, 'created' => false, 'path' => $target_path, 'message' => 'Directory could not be created.');
	}

	return array('success' => true, 'created' => true, 'path' => $target_path, 'message' => 'Directory created.');
}

/*
$result = ogSnippetCreateADirectory(__DIR__.'/storage', 'battlestar/flight-deck');
print_r($result);
*/