Tip: Store IP address as Integer in #MySQL


Updated July 12, 2013 ● 804 views
Here's how you store IP addres as integer in MySQL:

//if shared client
if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
    $ip=$_SERVER['HTTP_CLIENT_IP'];
}
//if proxy address<
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
    $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
    $ip=$_SERVER['REMOTE_ADDR'];
}
//convert ip to integer
$ip = ip2long($ip);

To read it as an IP, use to INET_NTOA function in MySQL:

SELECT INET_NTOA(ip) FROM 'user';

3 Comments

Sort by Best Controversial New
 
1
Great tip! I didn't know this. I used to store ip address as varchar. ross · 11 years ago
permalink · reply (0)
0
Thank you! This is very helpful. master_yii · 11 years ago
permalink · reply (1)
0
@master_yii: you are welcome :) admin · 11 years ago
permalink · reply

This website uses cookies. By continuing to use this site, you are accepting our Privacy Policy and Terms of Service.