There are many ways to get an IP address in PHP, below I introduce the use of Linux command to obtain an IP address and then convert the output of the array, the following is also introduced some common examples of PHP IP address processing.
PHP Gets the server IP address
Execute ifconfig with PHP to obtain the Linux server IP and output an array, the following is the code:
| The code is as follows |
Copy Code |
|
function Getserverip () {//Read the server IP with ifconfig and output an array
$SS = EXEC ('/sbin/ifconfig | sed-n ' s/^ *.*addr:\ ([0-9.] \{7,\}\). *$/\1/p ", $arr);
return $arr;
}
$ips =getserverip ();
foreach ($ips as $k = + $v) {//filter IP
if (substr ($v, 0,3) = = ' 127 ' | | substr ($v, 0,3) = = ', ' | | substr ($v, 0,7) = = ' 192.168 ' | | substr ($v, 0,6) = = ' 172.16 ') {
Unset ($ips [$k]);
}
}
Shuffle ($ips);//Reorder
Print_r ($ips);
?> |
Some PHP get IP address examples
| The code is as follows |
Copy Code |
|
function GetIP () {
if (!empty ($_server["Http_client_ip")) {
$cip = $_server["Http_client_ip"];
}
ElseIf (!empty ($_server["Http_x_forwarded_for")) {
$cip = $_server["Http_x_forwarded_for"];
}
ElseIf (!empty ($_server["REMOTE_ADDR")) {
$cip = $_server["REMOTE_ADDR"];
}
else{
$CIP = "Cannot get!" ";
}
return $CIP;
}
echo GetIP ();
?> |
I have a more common method here to get the User IP address:
| The code is as follows |
Copy Code |
function Get_user_ip () {
if (Isset ($_server[' http_client_ip ')) && $_server[' http_client_ip ']!= ' unknown ') {
$ip = $_server[' http_client_ip ');
} elseif (Isset ($_server[' http_x_forwarded_for ") && $_server[' http_x_forwarded_for ']!= ' unknown ') {
$ip = $_server[' http_x_forwarded_for ');
} else {
$ip = $_server[' remote_addr ');
}
return $IP;
} |
PHP Get IP location (call Sina API for IP location)
| The code is as follows |
Copy Code |
function Get_location ($IP) {
$curl = Curl_init ();
curl_setopt ($curl, Curlopt_url, "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=". $ip);
$location = curl_exec ($curl);
$location = Json_decode ($location);
if ($location ===false) return "";
return empty ($location->desc)? $location->province. $location->city. $location->district. $location->isp: $location->desc;
} |
http://www.bkjia.com/PHPjc/632798.html www.bkjia.com true http://www.bkjia.com/PHPjc/632798.html techarticle There are many ways to get an IP address in PHP, below I introduce the use of Linux command to obtain an IP address and then convert the output of the array, the following is also introduced some common examples of PHP IP address processing ...