加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 将相对URL转换为绝对URL

发布时间:2020-12-13 22:53:44 所属栏目:PHP教程 来源:网络整理
导读:假设我有一个链接到另一个文档的文档的URL(可以是绝对的或相对的),我需要绝对地使用此链接. 我做了一个简单的功能,为几种常见情况提供了这个功能: function absolute_url($url,$parent_url){ $parent_url=parse_url($parent_url); if(strcmp(substr($url,7)
假设我有一个链接到另一个文档的文档的URL(可以是绝对的或相对的),我需要绝对地使用此链接.

我做了一个简单的功能,为几种常见情况提供了这个功能:

function absolute_url($url,$parent_url){
  $parent_url=parse_url($parent_url);
  if(strcmp(substr($url,7),'http://')==0){
    return $url;
  }
  elseif(strcmp(substr($url,1),'/')==0){
    return $parent_url['scheme']."://".$parent_url['host'].$url;
  }
  else{
    $path=$parent_url['path'];
    $path=substr($path,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,这将无法正常工作.

那么有没有任何标准的类或函数可以更好地(更普遍)实现我的功能?

我尝试谷歌它并检查类似的问题(one和two),但它看起来像服务器路径相关的解决方案,这不是我正在寻找的东西.

解决方法

此函数将解析$pgurl中给定当前页面URL的相对URL而不使用正则表达式.它成功解决:

/home.php?example类型,

same-dir nextpage.php类型,

../…../…/parentdir类型,

完整的http://example.net网址,

和简写//example.net网址

//Current base URL (you can dynamically retrieve from $_SERVER)
$pgurl = 'http://example.com/scripts/php/absurl.php';

function absurl($url) {
 global $pgurl;
 if(strpos($url,'://')) return $url; //already absolute
 if(substr($url,2)=='//') return 'http:'.$url; //shorthand scheme
 if($url[0]=='/') return parse_url($pgurl,PHP_URL_SCHEME).'://'.parse_url($pgurl,PHP_URL_HOST).$url; //just add domain
 if(strpos($pgurl,'/',9)===false) $pgurl .= '/'; //add slash to domain if needed
 return substr($pgurl,strrpos($pgurl,'/')+1).$url; //for relative links,gets current directory and appends new filename
}

function nodots($path) { //Resolve dot dot slashes,no regex!
 $arr1 = explode('/',$path);
 $arr2 = array();
 foreach($arr1 as $seg) {
  switch($seg) {
   case '.':
    break;
   case '..':
    array_pop($arr2);
    break;
   case '...':
    array_pop($arr2); array_pop($arr2);
    break;
   case '....':
    array_pop($arr2); array_pop($arr2); array_pop($arr2);
    break;
   case '.....':
    array_pop($arr2); array_pop($arr2); array_pop($arr2); array_pop($arr2);
    break;
   default:
    $arr2[] = $seg;
  }
 }
 return implode('/',$arr2);
}

用法示例:

echo nodots(absurl('../index.html'));

在将URL转换为绝对值后,必须调用nodots().

点函数有点冗余,但是可读,快速,不使用正则表达式,并且将解析99%的典型网址(如果你想100%确定,只需扩展开关块以支持6点,虽然我从来没有在URL中看到过那么多点.

希望这可以帮助,

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读