How to get the IP address in php

In this tutorial you will learn how to get the IP address in php. Sometimes $_SERVER['REMOTE_ADDR'] cannot give you the exact IP address. If your visitor is connected to the Internet through Proxy Server then $_SERVER['REMOTE_ADDR'] just returns the IP address of the proxy server not of the visitor's machine. Let's have a look over how to get the almost real one.

How to get IP address in php

function getIpAddress()
{
    if (trim($_SERVER['HTTP_CLIENT_IP'])!="")   //checking ip address from share internet
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    else if (trim($_SERVER['HTTP_X_FORWARDED_FOR'])!="")   //checking whether ip address is pass from proxy
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

$ip_address = getIpAddress(); // Get the visitor's IP Address
echo $ip_address;

The above code snippet first tries to get the direct IP address of visitor’s machine, if not available then try for forwarded for IP address using HTTP_X_FORWARDED_FOR. And if this is not available too then it will finally get the IP address using REMOTE_ADDR. So that's it.


Happy Coding!!!

0 comments: