SoFunction
Updated on 2025-03-02

Two practical methods for converting ip address into decimal numbers in PHP

How to convert an IP address into a decimal number in PHP? Nowadays, IP addresses are often used in PHP, but this IP address is not decimal when obtaining it. So how to convert an IP address into a decimal number in PHP is a headache for us. The following two methods are the relatively simple method of converting IP addresses into a decimal number in my sorting process. Hope it will be helpful to everyone.
Method 1:
Copy the codeThe code is as follows:

public function ipToLong(){
$ip = $_SERVER['REMOTE_ADDR'];
$ip = explode('.', $ip);
$ip = array_reverse($ip);//Array inversion
$r = 0;
for($i=0,$j=count($ip); $i<$j; $i++){
$r += $ip[$i] * pow(256, $i);
}
$r = sprintf("%u", $r);
echo $r;
}

Method 2:
Copy the codeThe code is as follows:

public function ipToLong(){
$ip = $_SERVER['REMOTE_ADDR'];
$ip = explode('.',$ip);
$r = ($ip[0] << 24) | ($ip[1] << 16) | ($ip[2] << 8) | $ip[3];
if($r < 0) $r += 4294967296;
echo $r ;
}

The results of both results in the local server are 3232235877, and the IP used is 192.168.1.101. We use ping 192.168.1.101 and ping 3232235877 to check whether it is the same.