PHP most accurate / safe way to get real user IP address in 2017

后端 未结 10 479
粉色の甜心
粉色の甜心 2021-01-01 15:51

What is the most accurate way to get user\'s IP address in 2017 via PHP?

I\'ve read a lot of SO questions and answers about it, but most of answers are old and comme

10条回答
  •  孤街浪徒
    2021-01-01 16:29

    How about this one -

    public function getClientIP()
        {
            $remoteKeys = [
                'HTTP_X_FORWARDED_FOR',
                'HTTP_CLIENT_IP',
                'HTTP_X_FORWARDED',
                'HTTP_FORWARDED_FOR',
                'HTTP_FORWARDED',
                'REMOTE_ADDR',
                'HTTP_X_CLUSTER_CLIENT_IP',
            ];
    
            foreach ($remoteKeys as $key) {
                if ($address = getenv($key)) {
                    foreach (explode(',', $address) as $ip) {
                        if ($this->isValidIp($ip)) {
                            return $ip;
                        }
                    }
                }
            }
    
            return '127.0.0.0';
        }
    
    
        private function isValidIp($ip)
        {
            if (!filter_var($ip, FILTER_VALIDATE_IP,
                    FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)
                && !filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6 | FILTER_FLAG_NO_PRIV_RANGE)
            ) {
                return false;
            }
    
            return true;
        }
    

提交回复
热议问题