PHP获取公网IP地址的程序代码

作者:袖梨 2022-06-24

方法1:

获取客户端公网IP地址PHP

 代码如下 复制代码

/**
     * 获取真实IP地址
     */
    function get_real_ip(){
        if ( getenv( "HTTP_CLIENT_IP" ) && strcasecmp( getenv( "HTTP_CLIENT_IP" ), "unknown" ) ){
            $ip = getenv( "HTTP_CLIENT_IP" );
        }else if ( getenv( "HTTP_X_FORWARDED_FOR" ) && strcasecmp( getenv( "HTTP_X_FORWARDED_FOR" ), "unknown" ) ){
            $ip = getenv( "HTTP_X_FORWARDED_FOR" );
        }else if (getenv( "REMOTE_ADDR" ) && strcasecmp( getenv( "REMOTE_ADDR" ), "unknown" ) ){
            $ip = getenv( "REMOTE_ADDR" );
        }else if ( isset( $_SERVER[ 'REMOTE_ADDR' ] ) && $_SERVER[ 'REMOTE_ADDR' ]
            && strcasecmp( $_SERVER[ 'REMOTE_ADDR' ], "unknown" ) ){
            $ip = $_SERVER[ 'REMOTE_ADDR' ];
        }else{
            $ip = "unknown";
        }
        if ( strpos( $ip, ',' ) ){
            $ipArr = explode( ',', $ip );
            $ip = $ipArr[ 0 ];
        }
        return $ip;
}

方法2:

获取IP地址PHP

 代码如下 复制代码
function GetRealIP() {
    static $realip;
 
    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");
        }
    }
 
    if (strpos($realip, ',') === false) {
            $sUserIp = $realip;         
    } else {
     $arrUserIp = explode(',' , $realip);
     $sUserIp = $arrUserIp[0];
    }
    return $sUserIp;
}

 
两段代码的效果是一样的,不信大家可以试一下了都非常的好用了。

相关文章

精彩推荐