realpath() is just a system/library call to actual realpath() function supported by OS. It does not work on a path as a string, but also resolves symlinks. The resulting path might significantly differs from the input even when absolute path is given. No function in this notes resolves that.
The suggestion on the realpath man page is to look for an existing parent directory. Here is an example:
<?php
function resolvePath($path) {
if(DIRECTORY_SEPARATOR !== '/') {
$path = str_replace(DIRECTORY_SEPARATOR, '/', $path);
}
$search = explode('/', $path);
$search = array_filter($search, function($part) {
return $part !== '.';
});
$append = array();
$match = false;
while(count($search) > 0) {
$match = realpath(implode('/', $search));
if($match !== false) {
break;
}
array_unshift($append, array_pop($search));
};
if($match === false) {
$match = getcwd();
}
if(count($append) > 0) {
$match .= DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $append);
}
return $match;
}
?>
The result will retrieve absolute path for non-existing relative path. Even if a path does not exists, there should be existing directory somewhere, for which the realpath could be obtained. If this is not within the relative path (i.e. even current working directory does not exists), getcwd() will retrieve absolute path, so some absolute path is returned (although in that case the PHP process could have huge problems).