Safe Path Resolver Report
Resolves candidate file paths against an approved base directory and reports traversal or missing-path failures.
Purpose
Resolves candidate file paths against an approved base directory and reports traversal or missing-path failures.
Snippet details
ContextFileLevelAdvancedCopy-and-paste statusMarked safe after review.Categories
- Security
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.
*/
/**
* Safe Path Resolver Report.
*
* Purpose:
* Resolves candidate file paths against an approved base directory and reports traversal or missing-path failures.
*
* @param string $base_directory Approved base directory.
* @param array $candidate_paths Candidate relative paths.
* @return array Safe path resolution report.
*/
function ogSnippetSafePathResolverReport(string $base_directory, array $candidate_paths): array {
$base_real = realpath($base_directory);
$report = array();
if ($base_real === false) {
return array(array('status' => 'base_missing', 'path' => $base_directory));
}
foreach ($candidate_paths as $candidate_path) {
$clean_candidate = str_replace('\\', '/', (string) $candidate_path);
$joined = $base_real.'/'.ltrim($clean_candidate, '/');
$resolved = realpath($joined);
$status = 'missing';
if ($resolved !== false) {
$status = 'safe';
if (strpos($resolved, $base_real) !== 0) {
$status = 'outside_base';
}
}
$report[] = array('candidate' => $clean_candidate, 'resolved' => $resolved, 'status' => $status);
}
return $report;
}
$path_report = ogSnippetSafePathResolverReport(__DIR__, array('data-cache', '../outside-vault'));
echo count($path_report);