Home >Backend Development >PHP Problem >How to get the user's ip address in php

How to get the user's ip address in php

(*-*)浩
(*-*)浩Original
2019-09-20 11:04:0112422browse

IP Address: An Internet Protocol address (IP address) is a numerical label assigned to every device connected to a computer network that uses the Internet Protocol to communicate. An IP address has two main functions: host or network interface identification and location addressing.

How to get the user's ip address in php

$_SERVER['REMOTE_ADDR']: The IP address of the user’s computer browsing the current page

$_SERVER['HTTP_CLIENT_IP']: Client's ip (recommended learning: PHP programming from entry to proficiency)

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

$_SERVER['HTTP_X_REAL_IP']: In nginx proxy mode, get the real IP of the client

/**
 * 获取客户端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;
}

The above is the detailed content of How to get the user's ip address in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to encrypt phpNext article:How to encrypt php