2011-12-14 16:22

[PHP] 取得用戶真實 IP

轉載自:精進你的程式碼 - 從取得用戶端 IP 的函式談起

<?php
function get_client_ip(){
    foreach (array(
        'HTTP_CLIENT_IP',
        'HTTP_X_FORWARDED_FOR',
        'HTTP_X_FORWARDED',
        'HTTP_X_CLUSTER_CLIENT_IP',
        'HTTP_FORWARDED_FOR',
        'HTTP_FORWARDED',
        'REMOTE_ADDR'
    ) as $key) {
        if(!array_key_exists($key, $_SERVER)){ continue; }
        
        foreach (explode(',', $_SERVER[$key]) as $ip) {
            $ip = trim($ip);
            if ((bool) filter_var($ip, 
                FILTER_VALIDATE_IP,
                FILTER_FLAG_IPV4 |
                FILTER_FLAG_NO_PRIV_RANGE |
                FILTER_FLAG_NO_RES_RANGE
            )){ return $ip; }
        }
    }
    return null;
}

0 回應: