Have you ever wondered how can you get the IP of a user from behind a proxy that is not totally secure? Well look no more! here I will explain how to use PHP on your favor to fetch these! First, information for you newbsters. We will be using the "predefined super globals", the "explode()" function, the "isset()" function and the "empty()" function.
What happens is that some proxies send the IP in a HTTP header to the server, you just need to fetch it from the headers.
Note: Not ALL proxies do this, so it is NOT a 100% bullet proof.
First, we have the normal place where we get a IP, the "REMOTE_ADDR". This always (atleast on my case) returns a IP address, but if behind a proxy, then the proxy's IP will be here.
Then, we need to know what headers contain the IP. One of them is called "HTTP_FORWARDED_FOR", which holds the IP ready for retreival, with no special things to do needed.
After, comes the "HTTP_CLIENT_IP", which the IP is reversed, so you need to put it back to normal before using it.
Example:
|
<?php
$ip = ""; if ((isset($_SERVER['HTTP_X_FORWARDED_FOR'])) && (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } elseif ((isset($_SERVER['HTTP_CLIENT_IP'])) && (!empty($_SERVER['HTTP_CLIENT_IP']))) { $ip = explode(".",$_SERVER['HTTP_CLIENT_IP']); $ip = $ip[3].".".$ip[2].".".$ip[1].".".$ip[0]; } elseif ((!isset($_SERVER['HTTP_X_FORWARDED_FOR'])) && (empty($_SERVER['HTTP_X_FORWARDED_FOR'])) && (!isset($_SERVER['HTTP_CLIENT_IP'])) && (empty($_SERVER['HTTP_CLIENT_IP']))) { $ip = $_SERVER['REMOTE_ADDR']; } else { $ip = "0.0.0.0"; } ?> |
Explanation:
First, we clear the $ip var (something I always do, for security). Second, we check if "HTTP_FORWARDED_FOR" is set, and if it's not empty. If this is the case, return the IP and do nothing else. Third, we check if "HTTP_CLIENT_IP" is set, and if it's not empty also. If the IP is found here, we put it back to normal syntax and then return the IP and take no further action. Fourth, if both "HTTP_FORWARDED_FOR" and "HTTP_CLIENT_IP" are empty, then we pull the IP from "REMOTE_ADDR" as the last resource as there is no other possible solution. After all this, if ALL of the variables are empty or if there is a error, we return 0.0.0.0 as the IP, meaning that nothing was fetched. You call the IP that this snippet fetched using $ip in your code anywhere.



