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

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

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

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

复制代码代码示例:
//全局数组
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);
4 echo "<pre>";
5 print_r($arr);
6 echo "</pre>";
7 ?>

输出为数组,结果为:xcode

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正则表达式this

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 ?>
相关文章
相关标签/搜索