Get Remote IP Address in PHP

In case that you want to know the remote client IP address, you can simple get by referencing the global variables $_SERVER[‘REMOTE_ADDR’].

 

Following is the example to make function can get remote IP address.

  1: function getRemoteIPAddress() {
  2:     $ip = $_SERVER['REMOTE_ADDR'];
  3:     return $ip;
  4: }

 

But, the above function does not work correctly, if you are behind proxy server. In that case, below function to get real IP address of client.

  1: function getRealIPAddr()
  2: {
  3:     if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
  4:     {
  5:         $ip=$_SERVER['HTTP_CLIENT_IP'];
  6:     }
  7:     elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
  8:     {
  9:         $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
 10:     }
 11:     else
 12:     {
 13:         $ip=$_SERVER['REMOTE_ADDR'];
 14:     }
 15:     return $ip;
 16: }

Leave a Reply

Your email address will not be published. Required fields are marked *