Include and Require Files
Demonstrates allowlisted include/require loading so a caller can load an approved PHP file without accepting arbitrary paths.
Purpose
Demonstrates allowlisted include/require loading so a caller can load an approved PHP file without accepting arbitrary paths.
Snippet details
ContextFileLevelProductionCopy-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.
*/
/**
* Include and Require Files.
*
* Purpose:
* Loads an approved PHP module from a known directory using an allowlist and
* realpath checks before calling require_once.
*
* @param string $module_key Approved module key requested by the caller.
* @param string $base_directory Directory containing approved modules.
* @return array Load result and resolved file path.
*/
function ogSnippetIncludeAndRequireFiles(string $module_key, string $base_directory): array {
$allowed_modules = array(
'config' => 'config.php',
'helpers' => 'helpers.php',
'stargate-map' => 'stargate-map.php'
);
$module_key = trim($module_key);
if (isset($allowed_modules[$module_key]) === false) {
return array('success' => false, 'loaded' => false, 'path' => '', 'message' => 'Module key is not allowed.');
}
$base_path = realpath($base_directory);
if ($base_path === false || is_dir($base_path) === false) {
return array('success' => false, 'loaded' => false, 'path' => '', 'message' => 'Base directory is invalid.');
}
$candidate_path = realpath($base_path.DIRECTORY_SEPARATOR.$allowed_modules[$module_key]);
if ($candidate_path === false || is_file($candidate_path) === false) {
return array('success' => false, 'loaded' => false, 'path' => '', 'message' => 'Approved module file was not found.');
}
$base_prefix = $base_path.DIRECTORY_SEPARATOR;
if (strpos($candidate_path, $base_prefix) !== 0) {
return array('success' => false, 'loaded' => false, 'path' => '', 'message' => 'Resolved module path is outside the approved directory.');
}
require_once $candidate_path;
return array('success' => true, 'loaded' => true, 'path' => $candidate_path, 'message' => 'Approved module loaded.');
}
/*
$result = ogSnippetIncludeAndRequireFiles('helpers', __DIR__.'/includes');
print_r($result);
*/