user1877016
user1877016

Reputation: 19

My ip gets transformed when stored to mysql

I am writing a script that gets the visitors IP, removes the dots off it with explode, stores the IP without dots in the database, and then gets it and echoes it. But, my IP gets really messed up when I store it into the database.

HERE IS THE CODE!

EXAMPLE: My ip is 178.175.35.205 , without dots: 17817535205 , but when gone through MYSQL, I can even see it on PhpMyAdmin, is transformed to 2147483647.

UPDATE: Turns out everything was fine, but I was using INT except for BIGINT. That fixed it. I am now using ip2long and long2ip.

Upvotes: 1

Views: 222

Answers (3)

E_p
E_p

Reputation: 3144

Do not reinvent the wheel

use http://php.net/manual/en/function.ip2long.php and http://php.net/manual/en/function.long2ip.php functions to do conversions.

It would also validate it for you

$ipToStore =  ip2long($ip);
if (false !== $ipToStore) {
    // Store your ip
}

// Read DB
echo long2ip($ipFromDB);

Make sure in db to use BIGINT to store it.

http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html#integer-types

Upvotes: 4

Eric Petroelje
Eric Petroelje

Reputation: 60498

Your problem here is that the integer representation you are using is larger than what can be stored in an INT column in MySQL. In PHP you can use the ip2long function to convert an IP address to a proper 32 bit integer.

Upvotes: 0

paulsm4
paulsm4

Reputation: 121599

STRONG SUGGESTION:

1) Store the IP as a string

BENEFITS:

2) You can leave in the "."

... AND ...

3) You can accomodate either IPv4 and/or IPv6 addresses

IMHO..

Upvotes: 6

Related Questions