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

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – 将相对URL转换为绝对URL脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
假设我有一个链接到另一个文档的文档的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,这将无法正常工作.

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

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

解决方法

函数将解析$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中看到过那么多点.

希望这可以帮助,

脚本宝典总结

以上是脚本宝典为你收集整理的php – 将相对URL转换为绝对URL全部内容,希望文章能够帮你解决php – 将相对URL转换为绝对URL所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。