I'm working on a site that performs financial transactions. The transaction gateway allows you to optionally specify the customer's IP address with each transaction and this, in turn, supposedly allows more effective fraud prevention because the gateway tracks likely sources of fraudulent transactions.
This raises a question I have not investigated in some time. Which IP address is most important? I've seen numerous values sometimes specified in $_SERVER, any of which might contain the "best" IP address for the remote user:
- HTTP_CLIENT_IP
- HTTP_X_FORWARDED_FOR
- HTTP_X_FORWARDED
- HTTP_X_CLUSTER_CLIENT_IP
- HTTP_FORWARDED_FOR
- HTTP_FORWARDED
- REMOTE_ADDR
I've seen some folks report that REMOTE_ADDR can be their own proxy. I've seen others say that REMOTE_ADDR is the most reliable value and everything else is not to be trusted.
Will the real user IP please reveal itself? I hope that the august members of this forum might sound off on the this question and critique this function:
/**
* Get the users ip address
*
* @return string
*/
public static function get_ip_address()
{
$ip = null;
foreach (array(
'HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_X_CLUSTER_CLIENT_IP',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
'REMOTE_ADDR') as $key) {
if (array_key_exists($key, $_SERVER) === true) {
foreach (explode(',', $_SERVER [$key]) as $ip) {
if (filter_var($ip, FILTER_VALIDATE_IP) !== false) {
return $ip;
}
}
}
}
}
EDIT: I'd also like this function to work for scripts run via CLI rather than HTTPS. I see that $_SERVER has no keys related to my ip address when I run this command in a terminal:
php -r 'var_dump($_SERVER);'
EDIT2: When I login to a remote machine via SSH, I do see some entries with my IP:
["SSH_CLIENT"] => "11.11.11.11 55156 22"
["SSH_CONNECTION"] => "11.11.11.11 55156 10.239.1.1 22"
(ip addresses changed for privacy.