Getting Visitors IP Address in PHP

There are plethora of variables which can hold the Visitor IP address. One such variable is $_SERVER["REMOTE_ADDR"].
REMOTE_ADDR looks more close to our task as it has 'remote' inside it. But this variable can hold the private LAN IP address of the client machine's server network and which is not what we want to store in our Database.

These are few variables available in PHP, which will be useful in getting visitor's real IP address.

Get the Visitor's IP Address:

<?php
if ($_SERVER['HTTP_CLIENT_IP'])
	$visitorIP[] = $_SERVER['HTTP_CLIENT_IP'];
if ($_SERVER['HTTP_X_FORWARDED'])
	$visitorIP[] = $_SERVER['HTTP_X_FORWARDED'];
if ($_SERVER['HTTP_X_FORWARDED_FOR']) // when behind proxy
	$visitorIP[] = $_SERVER['HTTP_X_FORWARDED_FOR'];
	$visitorIP[] = $_SERVER['REMOTE_ADDR'];
?>

If you are behind proxy then HTTP_X_FORWARDED_FOR should give you local IP address (192.168.x.x) and REMOTE_ADDR should give you network IP address.
In case you did not find any value in say $_SERVER['HTTP_X_FORWARDED_FOR'] at your server, try using getenv() (ex. getenv('HTTP_X_FORWARDED_FOR')).

IP address can be spoofed so better do not rely on it for security check. IP address is good for statistics or presenting some geoLocation based information to visitors.

Now, something about using the return value from the variables discussed above.
Variables for getting IP address (ex. $_SERVER['HTTP_X_FORWARDED_FOR'], $_SERVER['REMOTE_ADDR']) can return comma separated IP address. This is returned by transparent proxy, which does not hide client IP address.

Check if proxy has returned multiple IP address!

<?php
if (strpos($visitorIP, ',') !== false) {
    $ips = explode(',', $visitorIP);
    $visitorIP = trim($ips[0]); // taking the first one
}
?>

Before storing the IP address in DB, validate IP address format. IP address is return from client side, so it can be something else!

Is IP Address format valid?

<?php
if (ip2long($visitorIP) != -1 && ip2long($visitorIP) != false) {
   //IP format is valid
}
?>

Storing Visitor's IP address in Database/Table:

For storing IP address in table, it is a good idea to store it in long form:

<?php
     echo $ip =  ip2long($visitorIP);
?>

This way, you can easily compare IP address. With this method it is also possible to compare IP address in range:
If ($ip >= $minIP AND $ip <= $maxIP) {}

long2ip() will get you back the real IP address in dotted notation.

To more about storing visitor's IP address, you may like to visit Grant Burton's post..

You know that IP address can be spoofed. How?

Comments are open for an year period. Please, write here on Facebook page.