ip acquisition function of TP5 source code analysis

Recently, I am working on the system log function, and I need to get the ip of the logged in user, and the system is the function $request->ip() that TP5 already has to get the ip. Then I analyzed the function step by step in the interest and added a comment

    /**
     * Get client IP address
     * @param integer $type Return type 0 Return IP address 1 Return IPV4 address number
     * @param boolean $adv whether to obtain advanced mode (may be disguised)
     * @return mixed
     */
    public function ip($type = 0, $adv = false)
    {
        $type = $type ? 1 : 0; //Regularly judge whether to pass in the type=1 parameter, and then find the ipv4 address number
        static $ip = null; //Define as a static variable to prevent repeated calls
        if (null !== $ip) {
            return $ip[$type];
        }
        /*
         * There are several ways to get the client ip. When the user uses a proxy server, through $_SERVER['HTTP_X_FORWARDED_FOR'] or
         * $_SERVER['HTTP_CLIENT_IP'] to get, of course, the way to get ip not only includes these, but also getnv('REMOTE_ADDR'), etc.
         * */
        if ($adv) {
            / / Determine whether the user passes parameters to determine how to obtain the ip
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); //Wait until proxy ip and user's local ip
                $pos = array_search('unknown', $arr); //Filter and judge the obtained value
                if (false !== $pos) {
                    unset($arr[$pos]);
                }
                $ip = trim(current($arr));
            } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $ip = $_SERVER['HTTP_CLIENT_IP'];
            } elseif (isset($_SERVER['REMOTE_ADDR'])) {
                $ip = $_SERVER['REMOTE_ADDR'];
            }
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        // IP address legal verification
        $long = sprintf("%u", ip2long($ip));
        $ip   = $long ? [$ip, $long] : ['0.0.0.0', 0];
        return $ip[$type];
    }

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324980016&siteId=291194637