HOW to get the client IP address using PHP?

IP address: An Internet Protocol address (IP address) is a numerical label assigned to each device connected to a computer network that uses the Internet Protocol for communication. An IP address serves two principal functions: host or network interface identification and location addressing.

Internet Protocol version 4 (IPv4) defines an IP address as a 32-bit number. However, because of the growth of the Internet and the depletion of available IPv4 addresses, a new version of IP (IPv6), using 128 bits for the IP address, was developed in 1995, and standardized in December 1998. In July 2017, a final definition of the protocol was published. IPv6 deployment has been ongoing since the mid-2000s.

IP addresses are usually written and displayed in human-readable notations, such as 172.16.254.2 in IPv4, and 2001:db8:0:1234:0:567:8:1 in IPv6. The size of the routing prefix of the address is designated in CIDR notation by suffixing the address with the number of significant bits, e.g., 192.168.1.16/24, which is equivalent to the historically used subnet mask 255.255.255.0.

The IP address space is managed globally by the Internet Assigned Numbers Authority (IANA), and by five regional Internet registries. They are responsible in their designated territories for assignment to end users and local Internet registries, such as Internet service providers. IPv4 addresses have been distributed by IANA to the RIRs in blocks of approximately 16.8 million addresses each. Each ISP or private network administrator assigns an IP address to each device connected to its network.

Here’s how you can get the IP address of the client

function get_ip() {

  // Get real visitor IP behind CloudFlare network
  if ( isset( $_SERVER['HTTP_CF_CONNECTING_IP'] ) ) {
    $ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
  } elseif ( isset( $_SERVER['HTTP_X_REAL_IP'] ) ) {
    $ip = $_SERVER['HTTP_X_REAL_IP'];
  } elseif ( isset( $_SERVER['HTTP_CLIENT_IP'] ) ) {
    $ip = $_SERVER['HTTP_CLIENT_IP'];
  } elseif ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
  } elseif ( isset( $_SERVER['HTTP_X_FORWARDED'] ) ) {
    $ip = $_SERVER['HTTP_X_FORWARDED'];
  } elseif ( isset( $_SERVER['HTTP_FORWARDED_FOR'] ) ) {
    $ip = $_SERVER['HTTP_FORWARDED_FOR'];
  } elseif ( isset( $_SERVER['HTTP_FORWARDED'] ) ) {
    $ip = $_SERVER['HTTP_FORWARDED'];
  } else {
    $ip = isset( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : 'UNKNOWN';
  }

  return $ip;
}

Hope this helps you to get the IP address of client

Scroll to Top