What's the best practise to store IP's with PHP in MySQL database? There's a function called ip2long - but this is just for IPv4. But what about IPv6?
I know a php function that is for IPv6 IP's, but it doesn't work on Windows with PHP < Version 5.3
knittl was closer, instead of binary(16) use varbinary(16) as user196009 answered in a related question. It works for me. How?
Storing IP:
<?php
$query = "insert into stats(vis_ip, id_stat) values('" . inet_pton('66.102.7.104') . "', '1')"; // google's IP address
// using a PDO wrapper. http://www.phpclasses.org/package/5206-PHP-Execute-database-queries-from-parameters-using-PDO.html
include_once 'db.php';
$c = new DB();
$visit = $c->getResults($query); // stored as binary
?>
Retrieving IP:
<?php
$query = "SELECT `vis_ip` FROM `stats` WHERE `id_stat`=1";
// PDO wrapper
include_once 'db.php';
$c = new DB();
$stats = $c->getRow($query);
echo inet_ntop($stats->vis_ip); // outputs 66.102.7.104
?>
It should work with IPv6 addresses (I have an IPv4 connection). I'm not an expert so I don't know yet if varbinary length is correct, but how I said, it works for me.
In order to check if 'IPv6 Support' is enabled in your PHP version/host:
<?php
phpinfo(INFO_GENERAL); // http://php.net/manual/es/function.phpinfo.php
?>