PHP将相对路径URL转换为绝对路径URL

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 20:04   4690   0

在采集程序或者蜘蛛程序中经常会遇到一类问题,就是将网页中相对路径形式的URL转换为绝对路径形式的URL。例如在http://www.msphome.cn/blog/1/这个页面中,有一个URL链接为../index.php,那么我们要将它转换为http://www.msphome.cn/blog/index.php。下面给出了解决这类问题的代码。该程序能够成功处理各种URL,将其变成绝对形式。

<?php
$a = 'http://www.abc.com/a/index.html';
$b = '../abc/a.js';
echo format_url($b, $a);

function format_url($srcurl, $baseurl) {
  $srcinfo = parse_url($srcurl);
  if(isset($srcinfo['scheme'])) {
    return $srcurl;
  }
  $baseinfo = parse_url($baseurl);
  $url = $baseinfo['scheme'].'://'.$baseinfo['host'];
  if(substr($srcinfo['path'], 0, 1) == '/') {
    $path = $srcinfo['path'];
  }else{
    $path = dirname($baseinfo['path']).'/'.$srcinfo['path'];
  }
  $rst = array();
  $path_array = explode('/', $path);
  if(!$path_array[0]) {
    $rst[] = '';
  }
  foreach ($path_array AS $key => $dir) {
    if ($dir == '..') {
      if (end($rst) == '..') {
        $rst[] = '..';
      }elseif(!array_pop($rst)) {
        $rst[] = '..';
      }
    }elseif($dir && $dir != '.') {
      $rst[] = $dir;
    }
   }
  if(!end($path_array)) {
    $rst[] = '';
  }
  $url .= implode('/', $rst);
  return str_replace('\\', '/', $url);
}
?>
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP