Sunday, April 12, 2009

Detecting IP Address Behind The Proxy

This is the short tutorial for detecting the IP address of website's visitors. If you familiar with PHP, you can use the $_SERVER['REMOTE_ADDR'] superglobal variable to detect the visitor's IP address. What if the visitor is browsing from behind the proxy. Of course you will only get the proxy IP address not the real IP address of the visitor.

There is one more superglobal variable to detect the real IP address of the visitor. It is the $_SERVER['HTTP_X_FORWARDED_FOR'].

This simple program will demonstrate the detection of IP address and the IP address that "hidding" behind the proxy.

<?php
echo "<p>You came from <b>".$_SERVER['REMOTE_ADDR']."</b>.</p>";

if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  if (preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/i", $_SERVER['HTTP_X_FORWARDED_FOR'])) {
    echo "But, your real IP address is <b>".$_SERVER['HTTP_X_FORWARDED_FOR']."</b>.";
  }
  else{
    echo "But, your real IP address is unknown.";
  }
}
?>

This is the screenshot while the script was running.


No comments: