Here you go, I made this function and it works perfectly:
function getPath($path)
{
$url = "http".(!empty($_SERVER['HTTPS'])?"s":"").
"://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$dirs = explode('/', trim(preg_replace('/\/+/', '/', $path), '/'));
foreach ($dirs as $key => $value)
if (empty($value)) unset($dirs[$key]);
$parsedUrl = parse_url($url);
$pathUrl = explode('/', trim($parsedUrl['path'], '/'));
foreach ($pathUrl as $key => $value)
if (empty($value)) unset($pathUrl[$key]);
$count = count($pathUrl);
foreach ($dirs as $key => $dir)
if ($dir === '..')
if ($count > 0)
array_pop($pathUrl);
else
throw new Exception('Wrong Path');
else if ($dir !== '.')
if (preg_match('/^(\w|\d|\.| |_|-)+$/', $dir)) {
$pathUrl[] = $dir;
++$count;
}
else
throw new Exception('Not Allowed Char');
return $parsedUrl['scheme'].'://'.$parsedUrl['host'].'/'.implode('/', $pathUrl);
}
Example:
Let's say your current location is http://www.mywebsite.com/files/morefiles/movies
,
echo getPath('../songs');
OUTPUT
http://www.mywebsite.com/files/morefiles/songs
echo getPath('./songs/whatever');
OUTPUT
http://www.mywebsite.com/files/morefiles/movies/songs/whatever
echo getPath('../../../../../../');
In this case it will throw an exception.
NOTE
I use this regex '/^(\w|\d|\.| |_|-)+$/'
to check the path directories which mean that only digit, word characters, '.', '-', '_' and ' ' are allowed. An exception will be trown for others characters.
The path .///path
will be corrected by this function.
USEFUL