How to Get the Client IP Address in PHP

Frequently, it is necessary to gather the clients’ IP addresses for tracking activity or for some security purposes.

Using the $_SERVER Variable

The $_SERVER variable provides a simple and efficient way of getting user IP addresses. It encompasses an array, providing the server and environment-related information in PHP.

Let’s begin with the simplest way: applying the $_SERVER['REMOTE_ADDR']. It returns the user IP addresses. It can be run in the following way:

echo 'User IP - '.$_SERVER['REMOTE_ADDR'];

But note that, sometimes, it may return a wrong IP address of the user. The reason is using Proxy.

So, in such a situation, to get the correct IP address of the user, it is recommended to act like this:

function getUserIpAddr(){
    if(!empty($_SERVER['HTTP_CLIENT_IP'])){
        //ip from share internet
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    }elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
        //ip pass from proxy
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }else{
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

echo 'User Real IP - '.getUserIpAddr();

Getting IP Addresses of the Website

Also, it is possible to receive the IP address of any website by the URL. All you need to do is passing the website URL within the gethostbyname() function, like this:

1. <?php  
2. $ip_address = gethostbyname("www.google.com");  
3. echo "IP Address of Google is - ".$ip_address;  
4. echo "</br>";  
5. $ip_address = gethostbyname("www.javatpoint.com");  
6. echo "IP Address of javaTpoint is - ".$ip_address;  
7. ?>

Defining PHP Superglobals

Superglobals are variables that are always accessible no matter what scope they have. They can also be accessed from any class, function without doing something special.

$_SERVER also belongs to the super global variables.It is capable of holding information about paths, headers, as well as script locations. The entities inside that array are generated by the webserver. There are also other superglobal variables such as $GLOBALS, $_REQUEST, $_POST, $_GET, $_FILES, $_ENV, $_COOKIE, and $_SESSION .


Do you find this helpful?

Related articles