@Karolis provided the accepted answer, but that does not quite do what I read the question to be. For example, the following script:
<?php
include('Karolis-answer') ;
chdir('/home/username') ;
printf("%s\n", get_absolute_path('some/folder/below') ;
when executed, will produce:
some/folder/below
... which is not an absolute path. In his defense, Karolis alluded to this in his answer, saying "... contain no (back)slash at position 0"
The correct answer would be:
/home/username/some/folder/below
The following slight modification to @Karolis' answer would be:
function absolutePath(string $path, $startingFolder = null) : string {
// Credit to Karolis at https://mcmap.net/q/1110942/-absolute-path-without-symlink-resolution-keep-user-in-home-directory
if (is_null($startingFolder))
$startingFolder = getcwd() ;
$path = str_replace( [ '/', '\\' ], DIRECTORY_SEPARATOR, $path) ;
if (substr($path, 0, 1) != DIRECTORY_SEPARATOR)
$path = $startingFolder . DIRECTORY_SEPARATOR . $path ;
$parts = array_filter(explode(DIRECTORY_SEPARATOR, $path), 'strlen') ;
$absolutes = [] ;
foreach ($parts as $part) {
if ( $part == '.' )
continue ;
if ( $part == '..')
array_pop($absolutes) ;
else
$absolutes[] = $part ;
}
return DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $absolutes) ;
}
This still does not resolve symbolic links, but will resolve the "relative" portion of the passed value.