/** * Gets remote IP address. * * This is intended as a drop-in replacement for $_SERVER['REMOTE_ADDR'], * which takes in consideration proxy values, blindly trusted. * * @return string the remote address */ function get_remote_addr() { $candidates = ['HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'HTTP_FORWARDED', 'HTTP_FORWARDED_FOR', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_X_FORWARDED', 'REMOTE_ADDR']; foreach ($candidates as $candidate) { if (array_key_exists($candidate, $_SERVER)) { return extract_client_ip_from_header($_SERVER[$candidate]); } } return ''; }
/** * @covers ::extract_client_ip_from_header */ function test_extract_client_ip_from_header() { $values = ['10.0.0.3', '10.0.0.3,10.0.0.4', '10.0.0.3, 10.0.0.4', '10.0.0.3, 10.0.0.4, lorem ipsum dolor']; foreach ($values as $value) { $this->assertEquals('10.0.0.3', extract_client_ip_from_header($value)); } $this->assertEmpty(extract_client_ip_from_header('')); }