php 使用PHP存储在MySQL数据库中的IP地址

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6427786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:21:31  来源:igfitidea点击:

IP address storing in MySQL database using PHP

phpmysqldatabaseipfield

提问by user552828

what is the right field type for IP address in mysql? and what is the right way of storing it using PHP?

mysql 中 IP 地址的正确字段类型是什么?使用 PHP 存储它的正确方法是什么?

回答by Francois Deschenes

This tutorialmight help you.

本教程可能对您有所帮助。

The most efficient way of saving IPv4 addresses is with an INT field (not VARCHAR as you might expect). You convert them using PHP's ip2longand back using either MySQL's INET_NTOAfunction or PHP's long2ipfunction.

保存 IPv4 地址的最有效方法是使用 INT 字段(不是您可能期望的 VARCHAR)。您可以使用 PHP 转换它们ip2long,然后使用 MySQL 的INET_NTOA函数或 PHP 的long2ip函数将它们转换回来。

If you need to store IPv6, you'll want to use a BINARY field instead and PHP's inet_ptonfunction.

如果需要存储 IPv6,则需要使用 BINARY 字段和 PHP 的inet_pton函数。

回答by knittl

you can store them in a binary field with a length of 128 bits (16 bytes, BINARY(16)or VARBINARY(16)). to convert any ip address to its binary representation, you can use the php function inet_pton. this method will work for both IPv4 and IPv6 addresses. inet_ntopcan be used to get back the string representation of the stored ip address (regardless of version)

您可以将它们存储在长度为 128 位(16 字节BINARY(16)VARBINARY(16))的二进制字段中。要将任何 ip 地址转换为其二进制表示形式,您可以使用 php 函数inet_pton。此方法适用于 IPv4 和 IPv6 地址。inet_ntop可用于取回存储的 ip 地址的字符串表示(无论版本如何)

回答by Sander

Generally you can go with VARCHAR(45) as it will be long enough to even store IPv6.

通常,您可以使用 VARCHAR(45),因为它的长度足以存储 IPv6。