IP address storing in MySQL database using PHP

PhpMysqlDatabaseIpField

Php Problem Overview


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

Php Solutions


Solution 1 - Php

This tutorial might 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 ip2long and back using either MySQL's INET_NTOA function or PHP's long2ip function.

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

Solution 2 - Php

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_ntop can be used to get back the string representation of the stored ip address (regardless of version)

Solution 3 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser552828View Question on Stackoverflow
Solution 1 - PhpFrancois DeschenesView Answer on Stackoverflow
Solution 2 - PhpknittlView Answer on Stackoverflow
Solution 3 - PhpSanderView Answer on Stackoverflow