There are many ways to obtain the IP address in PHP. Below I will introduce the use of Linux commands to obtain the IP address and then convert it into an array for output. The following also introduces some common examples of PHP IP address processing.
PHP Get Server IP Address
Use PHP to execute ifconfig to obtain the Linux server IP and output it as an array. The following is the code:
The code is as follows | Copy code | ||||
$ss = exec('/sbin/ifconfig | sed -n 's/^ *.*addr:([0-9.]{7,}) .*$/1/p'',$arr);< br /> return $arr; } $ips=getServerIp(); foreach($ips as $k=>$v){//Filter IP if(substr($v,0,3)=='127' || substr($v,0,3)=='10.' || substr($v,0,7)=='192.168' | | substr($v,0,6)=='172.16'){ unset($ips[$k]); } } shuffle($ips);//Reorder print_r($ips); ?>
|
代码如下 | 复制代码 |
function GetIP(){ |
The code is as follows | Copy code |
function GetIP(){ |
I have a relatively common method to obtain the user’s IP address:
代码如下 | 复制代码 |
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 gets the IP location (call Sina API to get the IP location)
代码如下 | 复制代码 |
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; } |