本文介紹下,在php中,獲取域名以及域名對應的IP地址的方法,有需要的朋友參考下。
在php中可以使用內置函數gethostbyname獲取域名對應的IP地址,比如:
1 |
<?php |
2 |
echo 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
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 |
?> |
輸出為數組,結果為:
Array
(
[scheme] => http
[host] => www.jbxue.com
[path] => /index.php
[query] => referer=jbxue.com
)
(
[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 |
?> |
