本文介绍下,在php中,获取域名以及域名对应的IP地址的方法,有需要的朋友参考下。
在php中可以使用内置函数gethostbyname获取域名对应的IP地址,比如:
2 | echo gethostbyname("www.jbxue.com"); |
以上会输出域名所对应的的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函数;
2 | $url ="http://www.jbxue.com/index.php?referer=jbxue.com"; |
输出为数组,结果为:
Array
(
[scheme] => http
[host] => www.jbxue.com
[path] => /index.php
[query] => referer=jbxue.com
)
说明:
scheme对应着协议,host则对应着域名,path对应着执行文件的路径,query则对应着相关的参数;
方法3,采用自定义函数。
02 | $url ="http://www.jbxue.com/index.php?referer=jbxue.com"; |
04 | function get_host($url){ |
06 | $url=Str_replace("http://","",$url); |
07 | //获得去掉http://url的/最先出现的位置 |
08 | $position=strpos($url,"/"); |
09 | //如果没有斜杠则表明url里面没有参数,直接返回url, |
14 | echo substr($url,0,$position); |
方法4,使用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)){ |