php: getting ip address

前端 未结 3 1625
伪装坚强ぢ
伪装坚强ぢ 2021-01-20 14:57

I want to get an ip address of visitors. could you tell me what element of $_SERVER[] i should use?

$_SERVER[\'HTTP_CLIENT_IP\'];
$_SERVER[\'HTT         


        
相关标签:
3条回答
  • 2021-01-20 15:42

    It depends on if your application is behind a reverse proxy or something like that. The easiest thing to do is check all three and choose the one that is not one of your IPs.

    0 讨论(0)
  • 2021-01-20 15:46

    $_SERVER['REMOTE_ADDR'];

    According to the PHP documentation: The IP address from which the user is viewing the current page.

    This is the IP that is connected to your server (reported by your server).
    The other values are set by the client.

    The HTTP_X_FORWARDED_FOR is a non-standard header (hence the x-prefix), set by certain proxy-servers. It is an attempt by the big proxy server vendors to help ISPs identify abusive IP addresses; it contains a list with all forwarded-for IPs.

    I don't know the origin of the HTTP_CLIENT_IP header

    0 讨论(0)
  • 2021-01-20 15:56

    Use this:

    function getIP() {
      foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key) {
        if (array_key_exists($key, $_SERVER) === true) {
            foreach (explode(',', $_SERVER[$key]) as $ip) {
               if (filter_var($ip, FILTER_VALIDATE_IP) !== false) {
                  return $ip;
               }
            }
         }
       }
     }
    
    0 讨论(0)
提交回复
热议问题