Skip to content

Instantly share code, notes, and snippets.

@nagiyevelchin
Last active February 12, 2022 15:55
Show Gist options
  • Save nagiyevelchin/61b30a74bde533da1683f9bca0f73eb3 to your computer and use it in GitHub Desktop.
Save nagiyevelchin/61b30a74bde533da1683f9bca0f73eb3 to your computer and use it in GitHub Desktop.
Convert IP address to longint in PHP
<?php
/**
* IP to long
* @param type $ip
* @return int
*/
function ipToLong($ip = false) {
if (!$ip) {
$ip = getClientIPAddress();
}
$ip2long = ip2long($ip);
if ($ip2long < 0) {
$ip2long = sprintf('%u', $ip2long);
}
return $ip2long;
}
/**
* Retuns client's IP address
* @return string
* @since 6/16/11 12:11 PM
*/
function getClientIPAddress() {
if (getenv("HTTP_CLIENT_IP")) {
$ip = getenv("HTTP_CLIENT_IP");
} else {
if (getenv("HTTP_X_FORWARDED_FOR")) {
$ip = getenv("HTTP_X_FORWARDED_FOR");
} else {
if (getenv("REMOTE_ADDR")) {
$ip = getenv("REMOTE_ADDR");
} else {
$ip = "UNKNOWN";
}
}
}
return $ip;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment