Simple PHP Proxy Detection Script and Client Real IP Address

If you are not still aware; this server variable: $_SERVER[“REMOTE_ADDR”] cannot detect real IP address of the user if it is behind a proxy server.

Below is a sample PHP script that can detect if a user is using a proxy or not:

<?php
$remoteaddr=$_SERVER["REMOTE_ADDR"];
$xforward= $_SERVER["HTTP_X_FORWARDED_FOR"];
if (empty($xforward)) {
//user is NOT using proxy
echo "You are not using proxy, your real IP address is: $remoteaddr";
}
else {
echo "You are using a proxy, your proxy server IP is $remoteaddr while your real IP address is $xforward";
}
?>

So how does the above script works?

First, it defines the required variables:

a. ) $remoteaddr=$_SERVER[“REMOTE_ADDR”] ==> this is the IP address that is directly requesting to the server IF NOT behind a proxy.
b.) $xforward= $_SERVER[“HTTP_X_FORWARDED_FOR”] ==> this is the originating IP address IF behind a proxy server.

You can understand this pretty easily below:

Proxy detection using PHP script

Take note that in the first case, if the user in your server is not behind the proxy; the client real IP address can be detected using $_SERVER[“REMOTE_ADDR”]
but the problem is when the user tries to hide behind the proxy server.

In the second scenario, you can detect the client real IP address behind the proxy server by using $_SERVER[“HTTP_X_FORWARDED_FOR”] instead of $_SERVER[“REMOTE_ADDR”]

If the user is not using proxy; the value of $_SERVER[“HTTP_X_FORWARDED_FOR”] is EMPTY or null. If the user is using proxy, both $_SERVER[“REMOTE_ADDR”]
and $_SERVER[“HTTP_X_FORWARDED_FOR”] has values which you can evaluate.

Below is the standard script that can detect the real IP address of your website user with or without using a proxy:

<?php
$remoteaddr=$_SERVER["REMOTE_ADDR"];
$xforward= $_SERVER["HTTP_X_FORWARDED_FOR"];
if (empty($xforward)) {
//user is NOT using proxy
$real_ip_address = $remoteaddr;
}
else {
//user is using proxy
$real_ip_address = $_SERVER["HTTP_X_FORWARDED_FOR"];
}
?>

The above script is pretty useful if you are limiting the download limit per IP address. If some malicious users attempt to abuse your system using proxy, then above script can detect their real IP address.



Related posts: