将 IP 存储为无符号整数?
我读到在数据库中存储 IP 地址的最佳方法是创建一个 Unsigned Int(10) 字段。如何使用 PHP 转换 IP 地址?我尝试过使用
$this->ip = long2ip($_SERVER['REMOTE_ADDR']);
但这似乎不起作用。我找到了将其转换回 IP 地址的方法,使用
$this->ip = sprintf("%u", ip2long($result['ip']));
如何最初转换 IP 地址?我应该为此使用 PHP 吗?或者集成到MySQL查询中会更好吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
long2ip
将整数转换为 IP 格式,并ip2long
则相反。因此,使用
ip2long
将$_SERVER['REMOTE_ADDR']
转换为整数以将其存储在数据库中,并在读取该整数后使用long2ip
数据库:long2ip
converts an integer into the IP format andip2long
does the inverse.So use
ip2long
to convert$_SERVER['REMOTE_ADDR']
into an integer for storing it in the database and uselong2ip
after reading the integer from the database:最好将此逻辑放入 SQL 查询中:
然后在选择数据时隐藏地址:
Better put this logic in your SQL query:
And then covert address back when selecting data:
我用过这个
I used this
如果您使用 MySQL,则可以使用
INET_ATON
(ip2long 等效项)和INET_NTOA
(long2ip) 函数,而不是使用 PHP 进行处理:If you're using MySQL you can use the
INET_ATON
(ip2long equivalent) andINET_NTOA
(long2ip) functions rather than doing the processing with PHP:您需要使用
ip2long
转换 IP 的点分字符串版本,然后使用long2ip
返回。看起来你现在已经倒退了。You’ll want to convert the dotted string version of your IP using
ip2long
, and back usinglong2ip
. Looks like you have it backwards right now.