Use ip2long() when you need to converts an IPv4 address into its integer representation in a PHP application. The examples below show the actual operation and its limitations.
What Is ip2long() in PHP?
Converts an IPv4 address into its integer representation. The exact signature supported by your installation depends on its PHP version and enabled extensions.
Its syntax is:
ip2long(string $ip): int|false
Parameters and return value: The parameter types, optional arguments, references, and return type are shown in the signature above. Optional parameters are marked with an ellipsis in this reference signature.
Example 1: Basic Usage
<?php
echo sprintf("%u",ip2long("192.0.2.1"));
Output:
3221225985
Example 2: Different Input or Behavior
<?php
var_dump(ip2long("not-an-ip") === false);
Output:
bool(true)
Practical Example: Applying the Function
<?php
$ipAddress = "203.0.113.5"; $encoded = ip2long($ipAddress); echo $encoded === false ? "Invalid" : long2ip($encoded);
Output:
203.0.113.5
Important Behavior and Edge Cases
Signed integer representations differ across platforms; this function does not handle IPv6.
Comparison With Related Functions
| Approach | Difference |
|---|---|
ip2long() | Converts an IPv4 address into its integer representation. |
| Related operation | inet_pton() supports both IPv4 and IPv6 in a packed binary representation. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring the function-specific limitation | Signed integer representations differ across platforms; this function does not handle IPv6. |
| Confusing this function with a related operation | inet_pton() supports both IPv4 and IPv6 in a packed binary representation. |
Key Takeaways
- Converts an IPv4 address into its integer representation.
- Signed integer representations differ across platforms; this function does not handle IPv6.
- inet_pton() supports both IPv4 and IPv6 in a packed binary representation.
Use ip2long() for the specific operation demonstrated above. Check its prerequisites and handle failure conditions before using it with production data.