Home  >  Article  >  Backend Development  >  How to get the client's IP address in PHP? (code example)

How to get the client's IP address in PHP? (code example)

青灯夜游
青灯夜游forward
2018-11-22 15:26:272208browse

The content of this article is to introduce how PHP obtains the client’s IP address? (Code example), let everyone know how to obtain the IP address in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

First let’s understand the meaning of related variables:

$_SERVER['REMOTE_ADDR']:Browse the current page The ip address of the user's computer

$_SERVER['HTTP_CLIENT_IP']: The client's ip

$_SERVER['HTTP_X_FORWARDED_FOR']: The gateway of the user's computer browsing the current page

$_SERVER['HTTP_X_REAL_IP']:nginx proxy mode, Obtain the client's real IP

Let's introduce the method of obtaining the client's IP address in PHP through a simple code example.

/**
 *  获取客户端IP地址
 */
function real_ip()
{
    $ip = $_SERVER['REMOTE_ADDR'];
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
        foreach ($matches[0] AS $xip) {
            if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
                $ip = $xip;
                break;
            }
        }
    } elseif (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['HTTP_CF_CONNECTING_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CF_CONNECTING_IP'])) {
        $ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
    } elseif (isset($_SERVER['HTTP_X_REAL_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_X_REAL_IP'])) {
        $ip = $_SERVER['HTTP_X_REAL_IP'];
    }
    return $ip;
}

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

The above is the detailed content of How to get the client's IP address in PHP? (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete