function fixLink($url) {
$parts = parse_url($url);
if (empty($parts['path']) || empty($parts['scheme'])) {
return $url;
}
$parts['path'] = preg_replace('@[^/]+/\.\./@', '', $parts['path']);
$parts['path'] = preg_replace('@^/\.\./@', '/', $parts['path']);
$parts['scheme'] .= '://';
return implode('', $parts);
}
但是,以上并不能解决所有情况。更强大的版本是:
function fixLink($url) {
$parts = parse_url($url);
if (empty($parts['scheme']) || empty($parts['path'])) {
return $url;
}
$path = array();
foreach (explode('/', $parts['path']) as $i => $item) {
if ($item == '..') {
if (count($path) > 1) {
array_pop($path);
}
} else {
$path[] = $item;
}
}
$parts['scheme'] .= '://';
$parts['path'] = implode('/', $path);
return implode('', $parts);
}