How to detect the visitor's IP address using HTML?

前端 未结 6 773
暗喜
暗喜 2020-12-29 13:59

How can i detect the visitors IP Address using HTML for my website? I have a contactform.html and a formsent.html. And when formsent.html sends the contact info to my email

6条回答
  •  清歌不尽
    2020-12-29 14:27

    HTML is a markup language, so it doesn't have any variables.

    If you want to get it using PHP, you'll need to make use of the $_SERVER superglobal variable. A solution could be:

    echo $_SERVER["REMOTE_ADDR"];
    

    This actually gets the host ip, which would be your server.

    echo $_SERVER["REMOTE_ADDR"];

    This is the most basic however, and fails if the user is behind a proxy, as well as allowing them to trivially change it. A much much better method is to using something like:

    function get_ip_address() {
      // check for shared internet/ISP IP
      if (!empty($_SERVER['HTTP_CLIENT_IP']) && $this->validate_ip($_SERVER['HTTP_CLIENT_IP']))
       return $_SERVER['HTTP_CLIENT_IP'];
    
      // check for IPs passing through proxies
      if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
       // check if multiple ips exist in var
        $iplist = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        foreach ($iplist as $ip) {
         if ($this->validate_ip($ip))
          return $ip;
        }
       }
    
      if (!empty($_SERVER['HTTP_X_FORWARDED']) && $this->validate_ip($_SERVER['HTTP_X_FORWARDED']))
       return $_SERVER['HTTP_X_FORWARDED'];
      if (!empty($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']) && $this->validate_ip($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']))
       return $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
      if (!empty($_SERVER['HTTP_FORWARDED_FOR']) && $this->validate_ip($_SERVER['HTTP_FORWARDED_FOR']))
       return $_SERVER['HTTP_FORWARDED_FOR'];
      if (!empty($_SERVER['HTTP_FORWARDED']) && $this->validate_ip($_SERVER['HTTP_FORWARDED']))
       return $_SERVER['HTTP_FORWARDED'];
    
      // return unreliable ip since all else failed
      return $_SERVER['REMOTE_ADDR'];
     }
    
    function validate_ip($ip) {
         if (filter_var($ip, FILTER_VALIDATE_IP, 
                             FILTER_FLAG_IPV4 | 
                             FILTER_FLAG_IPV6 |
                             FILTER_FLAG_NO_PRIV_RANGE | 
                             FILTER_FLAG_NO_RES_RANGE) === false)
             return false;
         self::$ip = $ip;
         return true;
     }
    

    (http://stackoverflow.com/questions/1634782/what-is-the-most-accurate-way-to-retrieve-a-users-correct-ip-address-in-php)

    This correctly parses the HTTP_X_FORWARDED_FOR field as well as validating the IP to make sure it's of the right format, and not in a private block.

提交回复
热议问题