Purpose
The purpose of this tutorial is to show how to save a IPv4 / IPv6 address into a mySQL database as a varbinary(16) column, and also read and translate that binary data (prior to the 5+ version that has native INET functions) with PHP into human-readable form.
/* Get the IP Address */
$iptosave = "1.2.3.4";
$iptosavefiltered = preg_replace('[^a-zA-Z0-9\.:]', '', $iptosave);
/* Save IPv4 / IPv6 address to the database. In this example a varbinary(16) column called "ip" */
INSERT INTO ip_address (ip) VALUES ('" . inet_pton($iptosavefiltered) . "');
/* Read the IPv4 / IPv6 address from the database. The question mark is the unique id of the row. */
SELECT ipa.ip FROM ip_address ipa WHERE ipa.id = ?;
/* Convert the ip address that was saved in the database */
$iptoread = ipv46presentationFromBinary($row["ip"]);
/* Show the human-readable ip address */
print $iptoread;
/* This function takes a binary encoded IPv4 or IPv6 address (stored in mySQL as varbinary(16)) and converts it into human readable form. */
function ipv46presentationFromBinary($binvalue) {
/* For IPv6, avoid use of PHP's default inet_ntop behavior which is to convert an IPv4/IPv6 down to an approximate IPv4 address. */
$assembledippresentation = "";
$tmpconversion = inet_ntop($binvalue);
/* IPv6 Address; special handling to avoid automatic down-conversion to an IPv4. */
if (preg_match("/^:/", $tmpconversion)) {
$frombinhex = bin2hex($binvalue);
/* Add ":" notation */
$charcount = 0; $segment = "";
for ($a = 0; $a <= strlen($frombinhex); $a++) {
$segment = $segment . substr($frombinhex, $a, 1);
$charcount = $charcount + 1;
if ($charcount == 4) {
if (strlen($assembledippresentation) == 0) { $assembledippresentation = $segment; }
else { $assembledippresentation = $assembledippresentation . ":" . $segment; }
$charcount = 0; $segment = "";
}
}
/* Replace "0000" with "0" */
$assembledippresentation = str_replace("0000", "0", $assembledippresentation);
}
else {
/* Assume IPv4 and use PHP's inet_ntop */
$assembledippresentation = $tmpconversion;
}
return $assembledippresentation;
}