Skip to content

Instantly share code, notes, and snippets.

@lfbn
Last active April 4, 2022 04:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lfbn/d98f95a6bf63e52a850c4c62318c9c68 to your computer and use it in GitHub Desktop.
Save lfbn/d98f95a6bf63e52a850c4c62318c9c68 to your computer and use it in GitHub Desktop.
[[php] Get unsafe client IP]
<?php
/**
* Class UnsafeClientIpProvider
*/
class UnsafeClientIpProvider
{
/**
* @var array
*/
private $server;
/**
* UnsafeClientIpProvider constructor.
* @param array $server
*/
public function __construct(array $server)
{
$this->server = $server;
}
/**
* Method who retrieves the client IP of a request. Is inspired in the Wordpress approach.
* @return string
* @link https://developer.wordpress.org/reference/classes/wp_community_events/get_unsafe_client_ip/
*/
public function __invoke(): string
{
$clientIp = '';
// In order of preference, with the best ones for this purpose first.
$addressHeaders = array(
'HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_X_CLUSTER_CLIENT_IP',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
'REMOTE_ADDR',
);
foreach ($addressHeaders as $header) {
if (array_key_exists($header, $this->server)) {
/*
* HTTP_X_FORWARDED_FOR can contain a chain of comma-separated
* addresses. The first one is the original client. It can't be
* trusted for authenticity, but we don't need to for this purpose.
*/
$addressChain = explode(',', $this->server[$header]);
$clientIp = trim($addressChain[0]);
break;
}
}
if (!$clientIp === filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP)) {
return '';
}
return $clientIp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment