I’m developing a system where users are identified by their IP addresses, through this php script:
function visitorIP()
{
if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
$TheIp=$_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
$TheIp=$_SERVER['REMOTE_ADDR'];
}
return trim($TheIp);
}
$ip = visitorIP();
I wonder if this is a really safe way to retrieve the ip address. I’m not dealing with credit card numbers or money, so the system does not need to be super safe, but if this script is very easy to hack that could be a problem anyway. Thanks for any help.
The method you are using to get the IP is pretty standard for an Apache web server, however REMOTE_ADDR is not a reliable method to uniquely identify a user. Also as other people have noted, any of the ‘HTTP_*’ headers are easy to spoof.
The big issue is that identifying a user by IP Address is just plain problematic, and generally you wouldn’t do it in a large system where you expect to see lots of users. I can think of several situations off the top of my head where it breaks down:
It’s likely your situation could be handled a lot better using sessions. Assign a user a session token the first time you see them rather than using their IP address, and make sure the token is passed (via cookies or part of the HTTP requests) on subsequent requests. When you get the token, you can be fairly confident it’s the same user (sniffing attacks notwithstanding).
As an added bonus, you can combine IP tracking with sessions to make things more robust if you feel the need. For instance, a lot of applications will often try to figure out if a user’s IP has changed, and invalidate a session as a result.