W3docs

PHP ip2long() Function: Everything You Need to Know

As a PHP developer, you may need to convert an IP address from a human-readable format to a long integer. The ip2long() function is a built-in function in PHP

As a PHP developer, you may need to convert an IP address from a human-readable format to a long integer. The ip2long() function is a built-in PHP function that performs this conversion. This article covers its syntax, usage, and important caveats.

What is the ip2long() Function?

The ip2long() function converts a standard IPv4 address string into its corresponding 32-bit integer representation.

How to Use the ip2long() Function

Using the ip2long() function is straightforward. Here is the syntax:

The PHP syntax of ip2long() Function

ip2long($ip_address);

The function takes one parameter:

  • $ip_address: The IP address to be converted to a long integer.

Here is an example of how to use the ip2long() function with proper validation and unsigned formatting:

How to Use the ip2long() Function?

<?php

$ip_address = "127.0.0.1";
$long_integer = ip2long($ip_address);

if ($long_integer !== false) {
    // Use sprintf('%u') to ensure an unsigned integer representation
    echo sprintf('%u', $long_integer); // Outputs 2130706433
} else {
    echo "Invalid IP address";
}

In this example, we convert the IP address "127.0.0.1" to a long integer. We check if the result is false (which indicates invalid input) and use sprintf('%u', ...) to output the value as an unsigned integer.

Important Notes

  • Unsigned Output: ip2long() returns a signed 32-bit integer. For IP addresses in the upper range (e.g., 192.168.1.1), it may return a negative number. Always use sprintf('%u', ip2long($ip)) when storing or displaying the result.
  • IPv6 Support: ip2long() only supports IPv4 addresses. For IPv6, use the inet_pton() function instead.

Conclusion

The ip2long() function provides a straightforward way to convert IPv4 addresses to integers for storage or comparison. Remember to validate the return value and use sprintf('%u', ...) for consistent unsigned output. We hope this guide helps you implement IP address conversion effectively in your PHP applications.

Practice

Practice

What does the PHP function 'ip2long' do?