Search code examples
phpsecurityipunsafe

using $_SERVER['REMOTE_ADDR'] , $_SERVER['HTTP_CLIENT_IP'] & $_SERVER['HTTP_X_FORWARDED_FOR']


i'm coding web application and i wanna secure my customers accounts so i'll get their IPs and store them in the database

is that enough to use

$_SERVER['REMOTE_ADDR']

OR

It's better to use these

$_SERVER['HTTP_CLIENT_IP']

$_SERVER['HTTP_X_FORWARDED_FOR']

cuz i have read that last two aren't safe and REMOTE_ADDR is the best way to detect visitors IPs


Solution

  • This depends on how your users are accessing your web app. $_SERVER['REMOTE_ADDR'] provides the IP address of whatever endpoint connected to your server. If your site is behind a CDN (e.g. CloudFlare), this will be the IP of the CDN node, not the IP of your user.

    $_SERVER['HTTP_CLIENT_IP'] and $_SERVER['HTTP_X_FORWARDED_FOR'] are both set by a proxy server (such as a CDN cache) that exists between you and the client.

    Generally, the best option is to use HTTP_X_FORWARDED_FOR if present, and fall back to REMOTE_ADDR if HTTP_X_FORWARDED_FOR isn't set.

    [Edit: Note that clients accessing your site can add spoofed request headers - e.g. they might connect directly to your server, and supplying a forged X-Forwarded-For header. This header can't be trusted to be your user's actual IP. Unfortunately, there's no way to guarantee the IP that your webapp sees is actually the real IP of the user. There might be forged headers, NAT, etc. between you and them. Using some kind of IP filter can help to improve security, but it's not a solution on its own - you need something else as well.]