PHP获取域名、IP地址的方法

本文介绍下,在php中,获取域名以及域名对应的IP地址的方法,有需要的朋友参考下。
在php中可以使用内置函数gethostbyname获取域名对应的IP地址,比如:
1<?php
2echo gethostbyname("www.jbxue.com");
3?>

以上会输出域名所对应的的IP。
对于做了负载与cdn的域名来讲,可能返回的结果会有不同,这点注意下。

下面来说说获取域名的方法,例如有一段网址:http://www.jbxue.com/all-the-resources-of-this-blog.html
方法1,

复制代码代码示例:
//全局数组
echo $_SERVER[“HTTP_HOST”];
//则会输出www.jbxue.com

本地测试则会输出localhost。

方法2,使用parse_url函数;

1<?php
2$url ="http://www.jbxue.com/index.php?referer=jbxue.com";
3$arr=parse_url($url);
4echo "<pre>";
5print_r($arr);
6echo "</pre>";
7?>

输出为数组,结果为:

Array
(
[scheme] => http
[host] => www.jbxue.com
[path] => /index.php
[query] => referer=jbxue.com
)

说明:
scheme对应着协议,host则对应着域名,path对应着执行文件的路径,query则对应着相关的参数;

方法3,采用自定义函数。

01<?php
02    $url ="http://www.jbxue.com/index.php?referer=jbxue.com";
03    get_host($url);
04    function get_host($url){
05        //首先替换掉http://
06        $url=Str_replace("http://","",$url);
07        //获得去掉http://url的/最先出现的位置
08        $position=strpos($url,"/");
09        //如果没有斜杠则表明url里面没有参数,直接返回url,
10        //否则截取字符串
11        if($position==false){
12            echo $url;
13        }else{
14            echo substr($url,0,$position);
15        }
16    }
17?>

方法4,使用php正则表达式

1<?php
2    header("Content-type:text/html;charset=utf-8");
3    $url ="http://www.jbxue.com/index.php?referer=jbxue.com";
4    $pattern="/(http://)?(.*)//";
5    if(preg_match($pattern,$url,$arr)){
6        echo "匹配成功!";
7        echo "匹配结果:".$arr[2];
8    }
9?>
原文地址:https://www.cnblogs.com/linuxnotes/p/3332451.html