Tip: Store IP address as Integer in #MySQL


Updated July 12, 2013 ● 589 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 · 5 years ago
permalink · reply (0)
0
Thank you! This is very helpful. master_yii · 5 years ago
permalink · reply (1)
0
@master_yii: you are welcome :) admin · 5 years ago
permalink · reply



Our Terms of Use and Privacy Policy have changed.
By continuing to use this site, you are agreeing to the new Privacy Policy and Terms of Use.