您可以使用parse_url
得到的URL路徑:
$components = parse_url('http://DOMAIN/some/path/');
$path = $components['path'];
那麼你需要一種方法來標準化它。 This answer可以幫助你:那剩下來要做的就是重建URL
function normalizePath($path, $separator = '\\/')
{
// Remove any kind of funky unicode whitespace
$normalized = preg_replace('#\p{C}+|^\./#u', '', $path);
// Path remove self referring paths ("/./").
$normalized = preg_replace('#/\.(?=/)|^\./|\./$#', '', $normalized);
// Regex for resolving relative paths
$regex = '#\/*[^/\.]+/\.\.#Uu';
while (preg_match($regex, $normalized)) {
$normalized = preg_replace($regex, '', $normalized);
}
if (preg_match('#/\.{2}|\.{2}/#', $normalized)) {
throw new LogicException('Path is outside of the defined root, path: [' . $path . '], resolved: [' . $normalized . ']');
}
return trim($normalized, $separator);
}
的一切,你可以看到this comment:
function unparse_url($parsed_url) {
$scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
$host = isset($parsed_url['host']) ? $parsed_url['host'] : '';
$port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
$user = isset($parsed_url['user']) ? $parsed_url['user'] : '';
$pass = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : '';
$pass = ($user || $pass) ? "[email protected]" : '';
$path = isset($parsed_url['path']) ? $parsed_url['path'] : '';
$query = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
$fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
return "$scheme$user$pass$host$port/$path$query$fragment";
}
最終路徑:
$new_path = '../new_page';
if (strpos($new_path, '/') === 0) { // absolute path, replace it entirely
$path = $new_path;
} else { // relative path, append it
$path = $path . $new_path;
}
把它放在一起:
// http://DOMAIN/some/new_page
echo unparse_url(array_replace($components, array('path' => normalizePath($path))));
你真的需要推崇的URL的路徑? guzzle應該可以在不出現問題的情況下處理對「http:// DOMAIN/some/path /../ new_page」的請求 – Federkun
是的,我需要它進行其他驗證(而不是針對特定請求)。另外 - 如果'$ new_page'是'/ new_page',那麼最終的URL可能會有問題。 – Dekel