如果我知道当前站点路径,如何将URI转换为URL?
请考虑以下示例:
目前的路径是:`http://www.site.com/aa/folder/page1.php
Uri:folder2 / page.php
Uri:/folder2/page.php
如果当前路径是:
`http://www.site.com/aa/folder/
或
`http://www.site.com/aa/folder
那些网址会是什么样的?
我知道这应该是简单而明显的,但我找不到完整的答案(是的,我在Google上搜索过)
答案 0 :(得分:2)
$_SERVER
超全球将拥有您正在寻找的信息,即$_SERVER['REQUEST_URI']
和$_SERVER['SERVER_NAME']
。 $_SERVER['QUERY_STRING']
也可能有用。
请参阅:
答案 1 :(得分:2)
这是一段具有您需要的功能的代码块: http://ca.php.net/manual/en/function.parse-url.php#76682
编辑:使用示例
修改上述链接功能<?php
var_dump(resolve_url('http://www.site.com/aa/folder/page1.php','folder2/page.php?x=y&z=a'));
var_dump(resolve_url('http://www.site.com/aa/folder/page1.php','/folder2/page2.php'));
function unparse_url($components) {
return $components['scheme'].'://'.$components['host'].$components['path'];
}
/**
* Resolve a URL relative to a base path. This happens to work with POSIX
* filenames as well. This is based on RFC 2396 section 5.2.
*/
function resolve_url($base, $url) {
if (!strlen($base)) return $url;
// Step 2
if (!strlen($url)) return $base;
// Step 3
if (preg_match('!^[a-z]+:!i', $url)) return $url;
$base = parse_url($base);
if ($url{0} == "#") {
// Step 2 (fragment)
$base['fragment'] = substr($url, 1);
return unparse_url($base);
}
unset($base['fragment']);
unset($base['query']);
if (substr($url, 0, 2) == "//") {
// Step 4
return unparse_url(array(
'scheme'=>$base['scheme'],
'path'=>$url,
));
} else if ($url{0} == "/") {
// Step 5
$base['path'] = $url;
} else {
// Step 6
$path = explode('/', $base['path']);
$url_path = explode('/', $url);
// Step 6a: drop file from base
array_pop($path);
// Step 6b, 6c, 6e: append url while removing "." and ".." from
// the directory portion
$end = array_pop($url_path);
foreach ($url_path as $segment) {
if ($segment == '.') {
// skip
} else if ($segment == '..' && $path && $path[sizeof($path)-1] != '..') {
array_pop($path);
} else {
$path[] = $segment;
}
}
// Step 6d, 6f: remove "." and ".." from file portion
if ($end == '.') {
$path[] = '';
} else if ($end == '..' && $path && $path[sizeof($path)-1] != '..') {
$path[sizeof($path)-1] = '';
} else {
$path[] = $end;
}
// Step 6h
$base['path'] = join('/', $path);
}
// Step 7
return unparse_url($base);
}
?>
答案 2 :(得分:0)
php有pathinfo()
,realpath()
和parseurl()
以及其他文件系统和网址路径功能。与$_SERVER
超全球的信息一起使用(如andre所述),你应该能够做你需要的。
答案 3 :(得分:0)
$uri = "http://www.site.com/aa/folder/";
$url = explode("/", $uri);
$url = $url[2];
echo $url; //www.site.com
这是你在找什么?
答案 4 :(得分:0)
如果您安装PECL pecl_http
,则可以使用http_build_url
:
http_build_url("http://www.site.com/aa/folder/page1.php",
array("path" => "folder2/page.php"));
并将您的任何相对URI(L)传递为path
。该功能将确保构建正确的。