Get users IP address using PHP

0
462
get ip-address using php

I have found many programmer asking about “How to get the IP address of User?” Well, this is not too complex as you might have thought. There are various process of getting IP address of user. The most common way used to get the IP address of user visiting your sites are as follow.

$ip_address = $_SERVER["REMOTE_ADDR"];

or

$ip_address = getenv('REMOTE_ADDR');

$_SERVER is an array containing information such as headers, paths, and script locations. You can find more information about the $_SERVER at Here. Getenv() gets the value of an environment variable. You can find more information about the Getenv() function at Here. Getenv() function returns the value of the environment variable or FALSE on an error.

Let’s dig a little about the IP. IP stands for Internet Protocol. Every machine on a network possesses a unique identifier. The unique identifier is used by computers to send data to specific computers on a network. Each computer on a network is identified by the IP address of the corresponding computer. Simply, there are two versions of IP address i.e. IPv4 and IPv6. IPv4 uses 32 bits to create a single unique address. IPv6 uses 128 bits to create a single unique address.

But when one is using Proxy, in this case, you need to run some extra code to get the IP address. You can try the below code to get the IP address.

You can either use getenv() function or $_SERVER function. Both helps to get the IP address of user. The main difference between them is that, getenv() uses PHP’s environment variable to get the IP address whereas $_SERVER function uses web server to get the IP address of user. You can find more detailed information about getenv() function in this link. Similarly, you can get more information about $_SERVER in this link Keep in mind, we can use both method to access the user’s IP address.

Method 1:

$ip_address = getenv('HTTP_CLIENT_IP')?:
              getenv('HTTP_X_FORWARDED_FOR')?:
              getenv('HTTP_X_FORWARDED')?:
              getenv('HTTP_FORWARDED_FOR')?:
              getenv('HTTP_FORWARDED')?:
              getenv('REMOTE_ADDR');

echo $ip_address;

Method 2:

$ip_address = $_SERVER('HTTP_CLIENT_IP')?:
              $_SERVER('HTTP_X_FORWARDED_FOR')?:
              $_SERVER('HTTP_X_FORWARDED')?:
              $_SERVER('HTTP_FORWARDED_FOR')?:
              $_SERVER('HTTP_FORWARDED')?:
              $_SERVER('REMOTE_ADDR');
              
echo $ip_address;

The output of the above code will be something like:

120.89.108.233

There is no hard and fast rule for determining IP address of user. You can write your own logic structure.
Please note that, for testing this code, you need to put in on live server. Since, the IP address of you local server is always 127.0.0.1 or something like that.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.