This article covers the available ways to get IP addresses using PHP script. The IP address is the unique address for the machines like a client, server, or proxy. In PHP, we can get an IP address in two ways. These are,
Both of the above two methods require some key values to get the IP address of the user. We can retrieve the machine address by sending the appropriate key value to any one of the above PHP controls. For example, If we want to get client IP address, then we need to call either getenv(‘HTTP_CLIENT_IP’) or $_SERVER[‘HTTP_CLIENT_IP’].
Now, let us discuss the above two methods of showing IP addresses in detail.
In this method, we are attempting to access the IP address as a server variable that is created remotely. These variables are stored in PHP’s $_SERVER global array.
This global array expects various key indexes to get an IP address. Those possible key indexes are listed below.
Following PHP program is used to get the IP address of the user by using the above possible reserved keys as the index of the $_SERVER array.
<?php
function showIPAddress()
{
$variableIndex = array(
"HTTP_CLIENT_IP",
"HTTP_X_FORWARDED_FOR",
"HTTP_X_FORWARDED",
"HTTP_FORWARDED_FOR",
"HTTP_FORWARDED",
"REMOTE_ADDR"
);
for ($i = 0; $i < count($variableIndex); $i ++) {
if (! isset($ipAddress)) {
if (array_key_exists($variableIndex[$i], $_ENV)) {
$ipAddress = $_SERVER[$variableIndex[$i]];
echo $ipAddress;
break;
}
}
}
}
showIPAddress();
?>
In the above PHP program, the $variableIndex array holds all possible reserved keys to find the IP address. This array will be iterated to use each of its values in the $_SERVER array until the $ipAddress variable is set. Once a $ipAddress variable is set, we can break the loop.
Instead of accessing server variables, this second method is used to get environment variables by using the PHP getenv() method.
By using the same set of PHP reserved keys, the IP addresses will be found by using getenv() function. So, in the above program, we are required to replace $_SERVER[] with getenv() function call. Now, the program will be as shown below.
<?php
function showIPAddress()
{
$variableIndex = array(
"HTTP_CLIENT_IP",
"HTTP_X_FORWARDED_FOR",
"HTTP_X_FORWARDED",
"HTTP_FORWARDED_FOR",
"HTTP_FORWARDED",
"REMOTE_ADDR"
);
for ($i = 0; $i < count($variableIndex); $i ++) {
if (! isset($ipAddress)) {
if (array_key_exists($variableIndex[$i], $_SERVER)) {
$ipAddress = getenv($variableIndex[$i]);
echo $ipAddress;
break;
}
}
}
}
showIPAddress();
?>
Though, both methods are used to get an IP address, except case-insensitivity getenv() function on accepting PHP reserved keys like HTTP_CLIENT_IP. So, if we are not sure about the case of the reserved key indexes, then, accessing the environment variable would be the preferred method.