1. 程式人生 > >php獲取使用者和伺服器ip及其地理位置詳解

php獲取使用者和伺服器ip及其地理位置詳解

瀏覽器訪問獲取使用者ip:

/**
 * php獲取使用者真實 IP
 * 注意這種方式只適用於瀏覽器訪問時
 */
function getIP()
{
    if (isset($_SERVER)){
        if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
            $realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
        } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
            $realip = $_SERVER["HTTP_CLIENT_IP"];
        } else {
            $realip = $_SERVER["REMOTE_ADDR"];
        }
    } else {
        if (getenv("HTTP_X_FORWARDED_FOR")){
            $realip = getenv("HTTP_X_FORWARDED_FOR");
        } else if (getenv("HTTP_CLIENT_IP")) {
            $realip = getenv("HTTP_CLIENT_IP");
        } else {
            $realip = getenv("REMOTE_ADDR");
        }
    }
    return $realip;
}

注意: 
1、以上方式只適用於用瀏覽器訪問後臺服務時可用 
2、以瀏覽器訪問和在後臺直接執行php指令碼所生成的 $_SERVER 變數是不同的

後臺指令碼執行獲取伺服器ip:

<?php
/**
*方法一:使用 gethostbyname() 方法,此方法獲取的是內網ip
*/
$realip =  gethostbyname(gethostname());
print_r($realip);

echo "\n";

/**
*方法二:php執行linux系統命令 ifconfig 
* 利用正則表示式獲取 ip
*/

$output = shell_exec('ifconfig');
preg_match("/\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}/",$output,$realip );
print_r($realip [0]);

/**
*方法三:php執行linux系統命令 ifconfig ,此方法獲取外網ip
* 利用grep獲取 ip
*/
$shell = "/sbin/ifconfig | grep -oP '(?<=addr:).*(?=\s+B)' | sed '1d'";
$output = shell_exec($shell);
$shell = "/sbin/ifconfig | grep -oP '(?<=addr:).*(?=\s+B)'";
$output = exec($shell);
return $output;

?>

注意: 
1、gethostname() 獲取的是 eth0 的ip,虛擬機器下linux沒有eth0項,所以當在虛擬機器下執行該方法時返回 127.0.0.1

其他方法解釋:

gethostbyname(string $hostname) : 獲取對應主機名的一個ipv4地址

gethostbyaddr ( string $ip_address ) : 獲取指定的IP地址對應的主機名

gethostbynamel ( string $hostname ) : 獲取對應主機名的一系列所以ipv4地址

php獲取ip所屬城市:
/**
 * php獲取 IP  地理位置
 * 淘寶IP介面
 * @Return: array
 */
function getCity($ip = '')
{
    if($ip == ''){
        $url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json";
        $ip=json_decode(file_get_contents($url),true);
        $data = $ip;
    }else{
        $url="http://ip.taobao.com/service/getIpInfo.php?ip=".$ip;
        $ip=json_decode(file_get_contents($url));
        if((string)$ip->code=='1'){
            return false;
        }
        $data = (array)$ip->data;
    }

    return $data['city'];
}