[PHP]取得用戶IP

主要有2個方式可以取得用戶的IP,分別為 getenv()$_SERVER
不過 getenv() 不支援 IIS 的 ISAPI

getenv():

function get_client_ip() { 
    $client_ip = '';
    if (getenv('HTTP_CLIENT_IP'))
        $client_ip = getenv('HTTP_CLIENT_IP');
    else if(getenv('HTTP_X_FORWARDED_FOR'))
        $client_ip = getenv('HTTP_X_FORWARDED_FOR');
    else if(getenv('HTTP_X_FORWARDED'))
        $client_ip = getenv('HTTP_X_FORWARDED');
    else if(getenv('HTTP_X_CLUSTER_CLIENT_IP'))
        $client_ip = getenv('HTTP_X_CLUSTER_CLIENT_IP');
    else if(getenv('HTTP_FORWARDED_FOR'))
        $client_ip = getenv('HTTP_FORWARDED_FOR');
    else if(getenv('HTTP_FORWARDED'))
       $client_ip = getenv('HTTP_FORWARDED');
    else if(getenv('REMOTE_ADDR'))
        $client_ip = getenv('REMOTE_ADDR');
    else if(getenv('HTTP_VIA'))
        $client_ip = getenv('HTTP_VIA');
    else
        $client_ip = '無法取得資訊';
    return $client_ip;
}

$_SERVER:

function get_client_ip() {
    $client_ip = '';
    if (isset($_SERVER['HTTP_CLIENT_IP']))
        $client_ip = $_SERVER['HTTP_CLIENT_IP'];
    else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        $client_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_X_FORWARDED']))
        $client_ip = $_SERVER['HTTP_X_FORWARDED'];
    else if(isset($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']))
        $client_ip = $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
    else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
        $client_ip = $_SERVER['HTTP_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_FORWARDED']))
        $client_ip = $_SERVER['HTTP_FORWARDED'];
    else if(isset($_SERVER['REMOTE_ADDR']))
        $client_ip = $_SERVER['REMOTE_ADDR'];
    else if(isset($_SERVER['HTTP_VIA']))
        $client_ip = $_SERVER['HTTP_VIA'];
    else
        $client_ip = '無法取得資訊';
    return $client_ip;
}

不同的狀況IP會出現在不同的地方
可以從這邊去測試從哪可以抓到IP:http://www.gocar.idv.tw/tools/whatismyip.php

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *