【发布时间】:2014-12-12 23:18:38
【问题描述】:
假设我有一个链接到另一个文档的文档的 URL(可以是绝对的或相对的),我需要这个链接是绝对的。
我制作了一个简单的函数,为几种常见情况提供此功能:
function absolute_url($url,$parent_url){
$parent_url=parse_url($parent_url);
if(strcmp(substr($url,0,7),'http://')==0){
return $url;
}
elseif(strcmp(substr($url,0,1),'/')==0){
return $parent_url['scheme']."://".$parent_url['host'].$url;
}
else{
$path=$parent_url['path'];
$path=substr($path,0,strrpos($path,'/'));
return $parent_url['scheme']."://".$parent_url['host']."$path/".$url;
}
}
$parent_url='http://example.com/path/to/file/name.php?abc=abc';
echo absolute_url('name2.php',$parent_url)."\n";
// output http://example.com/path/to/file/name2.php
echo absolute_url('/name2.php',$parent_url)."\n";
// output http://example.com/name2.php
echo absolute_url('http://name2.php',$parent_url)."\n";
// output http://name2.php
代码可以正常工作,但可能有更多情况,例如 ../../path/to/file.php 不起作用。
那么有没有标准的类或函数比我的函数做得更好(更通用)?
【问题讨论】:
-
..\..\path\to\file.php是文件路径,而不是 url,因此需要单独的函数。 -
@Steve 所以
<a href='..\..\path\to\file.php'>file</a>在 HTML 文档中不起作用? -
它可能,取决于浏览器,但不能保证。 uri(您在链接中放置的内容)应使用正斜杠。我不想尴尬,我真的以为你在谈论文件路径,例如用于 phps include 等。
-
@Steve 哦!你说得对!我说的是URI。所以我的意思是
../../path/to/file.php
标签: php url normalization