Home > Article > Backend Development > There is a bug in PHP's ip2long, please use it with caution_PHP Tutorial
First take a look at the PHP code below. This section uses the ip2long function to convert the same IP. Of course, some people think that 58.99.011.1 and 058.99.011.1 are not legal
IP, then Return, this article will not help you.
Why use IP with leading zeros: In order to query in the database, this can locate the location information corresponding to the IP in the IP library. Although it is not as efficient as integer IP query, it is intuitive after all.
view plaincopy to clipboardprint?
echo ip2long(58.99.11.1),"
"; //The output is 979569409
echo ip2long(58.99.011.1),"
"; //The output is 979568897
echo ip2long(058.99.11.1),"
"; //The output is empty
?>
echo ip2long(58.99.11.1),"
"; //The output is 979569409
echo ip2long(58.99.011.1),"
"; //The output is 979568897
echo ip2long(058.99.11.1),"
"; //The output is empty
?>
In PHP 4.x and 5.x, the results of IP conversion with leading zeros are incorrect.
The solution is to write your own function:
view plaincopy to clipboardprint?
function myip2long($ip){
$ip_arr = split(.,$ip);
$iplong = (16777216 * intval($ip_arr[0])) + (65536 * intval($ip_arr[1])) + (256 * intval($ip_arr[2])) + intval($ip_arr[3]) ;
Return $iplong;
}