When building up a PHP based website, backend application or service, we may need to trace the number of usage by tracking the visitors IP address, even though it could not be the best way to identify an unique user. At the time when I am writing this article, there are several ways to get IP from Google search.

  • $_SERVER[‘REMOTE_ADDR’]
  • $_SERVER[‘HTTP_CLIENT_IP’]
  • $_SERVER[‘HTTP_X_FORWARDED_FOR’]

$_SERVER[‘REMOTE_ADDR’]
This variable may return the real IP. The only problem is when users visit our PHP website behind a proxy. In this case, $_SERVER[‘REMOTE_ADDR’] will return the proxy ip instead.

$_SERVER[‘HTTP_CLIENT_IP’] and $_SERVER[‘HTTP_X_FORWARDED_FOR’]
For people who are using proxy, we are able to use these two variable. However, HTTP head information is not reliable as it can be manually set by client.

Code Example
On the internet, the following example code is very popular approach:

if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
    $ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
    $ip = $_SERVER['REMOTE_ADDR'];
}

Even though the HTTP head information can be faked and REMOTE_ADDR may not appear the real IP, we can still trust above code, as most of the time, normal people will not use proxy at home. 80% of them even don’t know what proxy is.

Test Your IP Address

Here is a very simple example to test IP address. Maybe you can change your network settings and try.
Test My IP

Previous PostNext Post

Leave a Reply

Your email address will not be published. Required fields are marked *