Skip to content

Commit 070225f

Browse files
committed
Update Request::getIp method
1 parent 669b053 commit 070225f

File tree

2 files changed

+29
-8
lines changed

2 files changed

+29
-8
lines changed

src/Request.php

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -892,18 +892,26 @@ public function getId() : ?string
892892
/**
893893
* Get the connection IP.
894894
*
895+
* @param bool $validate True to validate the IP address, otherwise false
896+
*
897+
* @throws RuntimeException for invalid IP address
898+
*
895899
* @return string
896900
*/
897-
public function getIp() : string
901+
public function getIp(bool $validate = true) : string
898902
{
899903
$key = $this->getIpKey();
900-
if ($key === 'HTTP_FORWARDED') {
901-
return $this->getIpFromHttpForwarded();
902-
}
903-
if ($key === 'HTTP_X_FORWARDED_FOR') {
904-
return $this->getIpFromHttpXForwardedFor();
904+
$ip = match($key) {
905+
'HTTP_FORWARDED' => $this->getIpFromHttpForwarded(),
906+
'HTTP_X_FORWARDED_FOR' => $this->getIpFromHttpXForwardedFor(),
907+
default => $_SERVER[$key]
908+
};
909+
if ($validate && !\filter_var($ip, \FILTER_VALIDATE_IP)) {
910+
throw new RuntimeException(
911+
"The value of {$key} is not a valid IP address"
912+
);
905913
}
906-
return $_SERVER[$key];
914+
return $ip;
907915
}
908916

909917
/**

tests/RequestTest.php

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -719,13 +719,26 @@ public function testIpKeyWithHttpForwarded() : void
719719
$_SERVER['HTTP_FORWARDED'] = 'for="[2001:db8:cafe::17]", for=192.0.2.43';
720720
self::assertSame('2001:db8:cafe::17', $this->request->getIp());
721721
$_SERVER['HTTP_FORWARDED'] = 'for="foo", for=192.0.2.43';
722-
self::assertSame('foo', $this->request->getIp());
722+
self::assertSame('foo', $this->request->getIp(false));
723723
$_SERVER['HTTP_FORWARDED'] = 'foo';
724724
$this->expectException(RuntimeException::class);
725725
$this->expectExceptionMessage('The IP address could not be get from the Forwarded header');
726726
$this->request->getIp();
727727
}
728728

729+
/**
730+
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Forwarded#using_the_forwarded_header
731+
*/
732+
public function testIpKeyWithHttpForwardedWithObfuscatedIdentifier() : void
733+
{
734+
$_SERVER['HTTP_FORWARDED'] = 'for="foo", for=192.0.2.43';
735+
$this->request->setIpKey('HTTP_FORWARDED');
736+
self::assertSame('foo', $this->request->getIp(false));
737+
$this->expectException(RuntimeException::class);
738+
$this->expectExceptionMessage('The value of HTTP_FORWARDED is not a valid IP address');
739+
$this->request->getIp();
740+
}
741+
729742
public function testIpKeyException() : void
730743
{
731744
$this->expectException(\InvalidArgumentException::class);

0 commit comments

Comments
 (0)