Skip to content
← Back to Snippets
Code

Controlled Include Map Without Autoload Magic

Resolves an include target from an explicit allowlisted map instead of building dynamic include paths or relying on autoload magic.

Purpose

Resolves an include target from an explicit allowlisted map instead of building dynamic include paths or relying on autoload magic.

Snippet details

ContextInclude ControlLevelProductionCopy-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.
 */

/**
 * Controlled Include Map Without Autoload Magic.
 *
 * Purpose:
 * Resolves an approved include path from a fixed map without dynamic path
 * construction or class autoload side effects.
 *
 * @param string $module_key Requested module key.
 * @param array $include_map Allowlisted module key to file path map.
 * @param string $base_dir Required base directory for resolved files.
 * @return array Include resolution result.
 */
function ogSnippetControlledIncludeMapWithoutAutoloadMagic(string $module_key, array $include_map, string $base_dir): array {
	$module_key = strtolower(trim($module_key));
	$base_dir = rtrim($base_dir, '/');

	$result = array(
		'allowed' => false,
		'module_key' => $module_key,
		'path' => '',
		'message' => 'Module is not allowed.'
	);

	if ($module_key === '') {
		$result['message'] = 'No module key was provided.';
		return $result;
	}

	if (array_key_exists($module_key, $include_map) === false) {
		return $result;
	}

	$path = (string) $include_map[$module_key];
	$resolved_base = realpath($base_dir);
	$resolved_path = realpath($path);

	if ($resolved_base === false || $resolved_path === false) {
		$result['message'] = 'Mapped file could not be resolved.';
		return $result;
	}

	if (strpos($resolved_path, $resolved_base) !== 0) {
		$result['message'] = 'Mapped file is outside the approved base directory.';
		return $result;
	}

	if (is_file($resolved_path) === false || is_readable($resolved_path) === false) {
		$result['message'] = 'Mapped file is not readable.';
		return $result;
	}

	$result['allowed'] = true;
	$result['path'] = $resolved_path;
	$result['message'] = 'Mapped file is approved for include.';

	return $result;
}

$module_map = array(
	'enterprise' => __FILE__,
	'stargate' => __FILE__
);

$include_result = ogSnippetControlledIncludeMapWithoutAutoloadMagic('enterprise', $module_map, __DIR__);

echo 'Include map result: '.$include_result['message'];