如何转换字符串';010101010';在PHP中转换为真正的二进制字符串
我想将IP地址存储到MySQL如何转换字符串';010101010';在PHP中转换为真正的二进制字符串,php,mysql,ipv6,ipv4,Php,Mysql,Ipv6,Ipv4,我想将IP地址存储到MySQLVARBINARY(16)中。我将二进制地址作为字符串'01001010010100101001010010100101' 当我将它插入MySQL时。我意识到这不会自动转换 在搜索了PHP手册之后,我很惊讶没有这个函数 需要您帮助将二进制字符串转换为VARBINARY 您可以通过组合功能inet\u ntoa和conv来实现这一点 mysql> select inet_ntoa(conv('01001010010100101001010010100101',2
VARBINARY(16)
中。我将二进制地址作为字符串'01001010010100101001010010100101'
当我将它插入MySQL时。我意识到这不会自动转换
在搜索了PHP手册之后,我很惊讶没有这个函数
需要您帮助将二进制字符串转换为
VARBINARY
您可以通过组合功能inet\u ntoa
和conv
来实现这一点
mysql> select inet_ntoa(conv('01001010010100101001010010100101',2,10));
+----------------------------------------------------------+
| inet_ntoa(conv('01001010010100101001010010100101',2,10)) |
+----------------------------------------------------------+
| 74.82.148.165 |
+----------------------------------------------------------+
1 row in set (0.00 sec)
此外,字符串结果可以转换为二进制
:
mysql> select CAST(inet_ntoa(conv('01001010010100101001010010100101',2,10)) AS BINARY);
+--------------------------------------------------------------------------+
| CAST(inet_ntoa(conv('01001010010100101001010010100101',2,10)) AS BINARY) |
+--------------------------------------------------------------------------+
| 74.82.148.165 |
+--------------------------------------------------------------------------+
1 row in set (0.00 sec)
此外,使用
UPDATE
或INSERT
可以轻松地将该BINARY
字符串放入VARBINARY(16)
列。在PHP中,您可以使用bindec
和long2ip
将二进制字符串转换为IPv4地址:
-返回二进制字符串参数表示的二进制数的十进制等效值
-将长整数地址转换为(IPv4)Internet标准点格式的字符串
$ip_as_int = bindec('01001010010100101001010010100101');
$ipv4 = long2ip ( $ip_as_int );
echo $ipv4;
74.82.148.165
谢谢大家!但我认为我找到了一个更好的解决方案:6年前有人在PHP手册页面上发布:
结果是IP地址的二进制表示吗?结果是varbinary值吗?对不起。内容是从原始URL复制的。
<?php
function bin2bstr($input)
// Convert a binary expression (e.g., "100111") into a binary-string
{
if (!is_string($input)) return null; // Sanity check
// Pack into a string
return pack('H*', base_convert($input, 2, 16));
}
function bstr2bin($input)
// Binary representation of a binary-string
{
if (!is_string($input)) return null; // Sanity check
// Unpack as a hexadecimal string
$value = unpack('H*', $input);
// Output binary representation
return base_convert($value[1], 16, 2);
}
// Returns string(3) "ABC"
var_dump(bin2bstr('01000001 01000010 01000011'));
// Returns string(24) "010000010100001001000011"
var_dump(bstr2bin('ABC'));
?>