Search code snippets, questions, articles...

How to Use PHP to Get the Client IP Address

When PHP is used to get the client IP address, it is first important to understand what an IP address is. An IP address is a unique number that is assigned to each device that is connected to the internet. This number is used to identify the device and allow it to communicate with other devices on the network.
<?php
	// create a function to get the client IP
  function get_ip_address() {
      $client_ip = '';
      if (getenv('HTTP_CLIENT_IP'))
          $client_ip = getenv('HTTP_CLIENT_IP');
      else if(getenv('HTTP_X_FORWARDED_FOR'))
          $client_ip = getenv('HTTP_X_FORWARDED_FOR');
      else if(getenv('HTTP_X_FORWARDED'))
          $client_ip = getenv('HTTP_X_FORWARDED');
      else if(getenv('HTTP_FORWARDED_FOR'))
          $client_ip = getenv('HTTP_FORWARDED_FOR');
      else if(getenv('HTTP_FORWARDED'))
         $client_ip = getenv('HTTP_FORWARDED');
      else if(getenv('REMOTE_ADDR'))
          $client_ip = getenv('REMOTE_ADDR');
      else
          $client_ip = 'UNKNOWN';
      return $client_ip;
  }
  
  // print ip address
  echo get_ip_address();
?>
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

The client's IP address can be helpful for a number of reasons. For example, it can be used to track the location of a user, to block access to specific sites or content, or to customize content based on the user's location.

To get the client IP address in PHP, the $_SERVER['REMOTE_ADDR'] variable can be used. This variable will contain the IP address of the user that is accessing the page.

Was this helpful?
0 Comments