Skip to content

Instantly share code, notes, and snippets.

@dimaslanjaka
Last active December 20, 2022 00:33
Show Gist options
  • Save dimaslanjaka/a6aa24a8fa7a13999ee3dac077fa21fe to your computer and use it in GitHub Desktop.
Save dimaslanjaka/a6aa24a8fa7a13999ee3dac077fa21fe to your computer and use it in GitHub Desktop.
PHP IP Utility
<?php
function anonIp($ip)
{
if (strpos($ip, ".") !== false) { // detect IP type by dots instead of length
$pieces = explode(".", $ip);
$nPieces = count($pieces);
$pieces[$nPieces - 1] = $pieces[$nPieces - 2] = "XXX";
return implode(".", $pieces);
} else {
$pieces = explode(":", $ip);
$nPieces = count($pieces);
$pieces[$nPieces - 1] = $pieces[$nPieces - 2] = "XXXX";
return implode(":", $pieces);
}
}
<?php
/**
* Detect is localhost
*
* @return boolean
*/
function isLocalHost()
{
$whitelist = [
'127.0.0.1',
'::1',
];
return in_array($_SERVER['REMOTE_ADDR'], $whitelist);
}
/**
* Get client ip, when getenv supported (maybe cli)
*
* @return string
*/
function get_client_ip()
{
$ipaddress = '';
if (isLocalHost()) {
$ipaddress = getLocalIp();
} else {
if (getenv('HTTP_CLIENT_IP')) {
$ipaddress = getenv('HTTP_CLIENT_IP');
} elseif (getenv('HTTP_X_FORWARDED_FOR')) {
$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
} elseif (getenv('HTTP_X_FORWARDED')) {
$ipaddress = getenv('HTTP_X_FORWARDED');
} elseif (getenv('HTTP_FORWARDED_FOR')) {
$ipaddress = getenv('HTTP_FORWARDED_FOR');
} elseif (getenv('HTTP_FORWARDED')) {
$ipaddress = getenv('HTTP_FORWARDED');
} elseif (getenv('REMOTE_ADDR')) {
$ipaddress = $ipaddress = getenv('REMOTE_ADDR');
} else {
/**
* Return to method 2
*/
$ipaddress = get_client_ip2();
}
}
return $ipaddress;
}
/**
* Get client ip, when running on webserver
*
* @return void
*/
function get_client_ip2()
{
$ipaddress = '';
if (isLocalHost()) {
$ipaddress = getLocalIp();
} else {
if (isset($_SERVER['HTTP_CLIENT_IP'])) {
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
} elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
} elseif (isset($_SERVER['HTTP_X_FORWARDED'])) {
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
} elseif (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
} elseif (isset($_SERVER['HTTP_FORWARDED'])) {
$ipaddress = $_SERVER['HTTP_FORWARDED'];
} elseif (isset($_SERVER['REMOTE_ADDR'])) {
$ipaddress = $_SERVER['REMOTE_ADDR'];
} else {
$ipaddress = 'UNKNOWN';
}
}
return $ipaddress;
}
function getLocalIp()
{
if (defined('PHP_MAJOR_VERSION') && PHP_MAJOR_VERSION >= 5) {
$localIP = gethostbyname(gethostname());
} else {
$localIP = gethostbyname(php_uname('n'));
}
return $localIP;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment