本文介绍下,在php中,获取域名以及域名对应的IP地址的方法,有须要的朋友参考下。
在php中能够使用内置函数gethostbyname获取域名对应的IP地址,好比:
2 |
echo gethostbyname ( "www.jbxue.com" ); |
以上会输出域名所对应的的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函数;数组
2 |
$url = "http://www.jbxue.com/index.php?referer=jbxue.com" ; |
输出为数组,结果为:xcode
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正则表达式。this
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 )){ |