Reputation: 53
I read that the best way to store IP addresses in a database is to make an Unsigned Int(10) field. How do I convert the IP addresses using PHP? I've tried using
$this->ip = long2ip($_SERVER['REMOTE_ADDR']);
But this doesn't seem to work. I found the way to convert it back to an IP address using
$this->ip = sprintf("%u", ip2long($result['ip']));
How do I convert the IP Address initially? Should I be using PHP for this? Or would it be better to integrate into the MySQL query?
Upvotes: 3
Views: 5876
Reputation: 45932
Better put this logic in your SQL query:
INSERT INTO `table`
(`ip`)
VALUES
INET_ATON('192.168.0.1')
And then covert address back when selecting data:
SELECT INET_NTOA(`ip`)
FROM `table`
Upvotes: 12
Reputation: 655369
long2ip
converts an integer into the IP format and ip2long
does the inverse.
So use ip2long
to convert $_SERVER['REMOTE_ADDR']
into an integer for storing it in the database and use long2ip
after reading the integer from the database:
$long = ip2long($_SERVER['REMOTE_ADDR']);
$ip = long2ip($long);
Upvotes: 12
Reputation: 2592
If you're using MySQL you can use the INET_ATON
(ip2long equivalent) and INET_NTOA
(long2ip) functions rather than doing the processing with PHP:
Upvotes: 2
Reputation: 14696
You’ll want to convert the dotted string version of your IP using ip2long
, and back using long2ip
. Looks like you have it backwards right now.
$integer_ip = ip2long($_SERVER["REMOTE_ADDR"]); // => 1113982819
$dotted_ip = long2ip($integer_ip); // => "66.102.7.99"
Upvotes: 1
Reputation: 8241
I used this
function ip2int($ip) {
$a = explode(".",$ip);
return $a[0] * 256 * 256 * 256 + $a[1] * 256 * 256 + $a[2] * 256 + $a[3];
}
Upvotes: 2