Oihana PHP

isBasePath.php

Table of Contents

Functions

isBasePath()  : bool
Checks whether a given canonical path **lies inside** a base directory.

Functions

isBasePath()

Checks whether a given canonical path **lies inside** a base directory.

isBasePath(string $basePath, string $childPath) : bool

The comparison is done purely on canonicalized strings (see canonicalizePath()); the filesystem is not consulted.

Algorithm

  1. Canonicalize both $basePath and $ofPath.
  2. Right–trim the base (to avoid double slash issues).
  3. Append a trailing slash to both and use str_starts_with() to ensure the whole first segment matches – preventing false positives like /var/www-legacy being considered inside /var/www.
Parameters
$basePath : string

The supposed ancestor directory.

$childPath : string

The child path to test.

Tags
example
isBasePath( '/var/www' , '/var/www/site/index.php' ); // true
isBasePath( '/var/www' , '/var/www' );                // true (exact match)
isBasePath( '/var/www' , '/var/www-legacy' );         // false
isBasePath( 'C:/Users' , 'C:/Users/Bob/file.txt') ;   // true (Windows)
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
bool

True if childPath is equal to or contained in basePath.


        
On this page

Search results