PHP获取客户端的访问IP函数

 /**

 * 获取请求客户端IP

 * @return ip

 */

function httpIp(){

    if (getenv('SERVER_SOFTWARE') == 'nginx'){

        if (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')){

            $ip = getenv('REMOTE_ADDR');

        } elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')){

            $ip = getenv('HTTP_X_FORWARDED_FOR');

        } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')){

            $ip = $_SERVER['REMOTE_ADDR'];

        } elseif (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {

            $ip = getenv('HTTP_CLIENT_IP');

        } else {

            $ip = '127.0.0.1';

        }

    } else {

        if (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')){

            $ip = getenv('HTTP_X_FORWARDED_FOR');

        } elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')){

            $ip = getenv('REMOTE_ADDR');

        } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')){

            $ip = $_SERVER['REMOTE_ADDR'];

        } elseif (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {

            $ip = getenv('HTTP_CLIENT_IP');

        } else {

            $ip = '127.0.0.1';

        }

    }

    preg_match("/[\d\.]{7,15}/", $ip, $temp);

    $ip = $temp[0] ? $temp[0] : 'unknown';

    unset($temp);

    if (isset($_SERVER["HTTP_CDN_SRC_IP"])){

        $ip = $_SERVER["HTTP_CDN_SRC_IP"];

    }

    return $ip;

} 

你可能感兴趣的:(PHP)