What is the correct way to convert ip to integer in php?

Therefore, I need to store IP addresses in the database, but storing them in the form of bites is not very efficient and not very convenient for my purpose.

So ... How to convert ip to integer in php with minimal processing, because it will be done millions of times a day.

And of course, how can I convert back from integet to ip?

I know that this can be googled and there are some simple solutions, but I ask faster , and not just for β€œdo X, but you get Y”, because this is a pretty simple task.

+7
source share
3 answers

Use ip2long() and long2ip() . They are the fastest you can find in PHP because they are simply built on top of the corresponding C. functions.

+20
source

Use ip2long - this function works very fast, it just doesn't matter if you call it a million times a day. This is a library function, so it is well tested and reliable.

And, given your work time, this is by far the fastest solution in the entire universe.

+1
source

You can use int

$ip = ip2long($ip);

To save in mysql:

 $sql = "INSERT INTO user(ip) VALUES('$ip')"; $dbQuery = mysql_query($sql,$dbLink 

You can return ip later:

 SELECT INET_NTOA(ip) FROM 'user' WHERE 1 

inet_ntoa (expression):

Given the numerical IPv4 network address in byte order of the network, returns the dotted square representing the address as a binary string. INET_NTOA () returns NULL if it does not understand its argument.

mysql> SELECT INET_NTOA (167773449); -> '10 .0.5.9 '

+1
source

All Articles