views:

127

answers:

5

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?

+6  A: 

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);
Gumbo
Your explanation is correct but your usage in the snipped is incorrect.
codaddict
@codaddict: Oops, fixed it.
Gumbo
A: 

I used this

function ip2int($ip) {
    $a = explode(".",$ip);
    return $a[0] * 256 * 256 * 256 + $a[1] * 256 * 256 + $a[2] * 256 + $a[3];
}
San4ez
A: 

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"
Todd Yandell
+2  A: 

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:

chigley
+9  A: 

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`
Silver Light
+1, especially because that should also support IPv6 -- although that probably never becomes reality :/
Markus Winand
What is the advantage to using SQL over PHP?
Ian
Well, it's just better, to put database storage related logic in queries if that is possible. For example, if you upgrade your MySQL server to a new version and there will be some changes in the way that data is stored, those changes will be reflected in database functions as well. If you trust this logic to other tool, you might get a problem. But first of all, it's logical delegation of tasks, so that your code is more understandable.
Silver Light
@Markus IPv6 is a reality today. Rare enough that we can't bank on it, but common enough that we can't bank on it not being used either.
Jon Hanna