Guides
Last updated
July 25, 2025

5 Ways to Validate an IP Address in PHP

Nicolas Rios
Nicolas Rios
Table of Contents:
ON THIS PAGE
Get your free
IP validation
 API key now
stars rating
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

Validating IP addresses in PHP is a common task for ensuring application security and data quality. Here, you'll find five distinct methods for IP validation, complete with working code snippets. We also examine the pitfalls of these traditional approaches and show how Abstract API effectively solves these issues.

How to Implement IP Address Validation in PHP

This section details four different methods to validate IP addresses in PHP. Each approach has a specific use case, from simple checks to more complex pattern matching for custom policies.

Validation with `filter_var` and `FILTER_VALIDATE_IP`

PHP’s `filter_var` extension provides a reliable way to check IP addresses. It uses the same library as the core system for network functions, which ensures consistent handling of IPv4 and IPv6 addresses.

To perform the validation, you pass the "FILTER_VALIDATE_IP" flag to the function. You can also use a bitmask to scope the check for specific IP versions.

For example, the "FILTER_FLAG_IPV4" flag restricts validation to IPv4 addresses only. For IPv6, you can use a combination of flags like "FILTER_FLAG_IPV6" and "FILTER_FLAG_NO_RES_RANGE".

Flags like "FILTER_FLAG_NO_PRIV_RANGE" and "FILTER_FLAG_NO_RES_RANGE" let you block private and reserved address ranges. More details are available on the PHP manual page. These IPv6 tips offer further insight.

function isIp(string $ip, int $flags = 0): bool
{
    return filter_var($ip, FILTER_VALIDATE_IP, $flags) !== false;
}

Validation with `inet_pton` and `inet_ntop`

The `inet_pton()` function converts a human-readable IP address into its packed, in-addr.arpa format. It returns `false` if the input string is not a valid IPv4 or IPv6 address.

This makes the validation process straightforward. It also avoids extra memory allocation because no string manipulation happens if the parsing fails.

The function is dual-stack aware, so you do not need separate code paths for IPv4 and IPv6. The resulting binary data can be stored or later re-expanded with `inet_ntop()`. This is one of several ways to validate an IP.

function isIpBinary(string $ip): bool
{
    return inet_pton($ip) !== false;
}

Round-Trip Validation with `ip2long` and `long2ip`

This method works only for IPv4 addresses. The `ip2long()` function can tolerate non-standard syntaxes, such as "0x7f.1" or "0177.1", which can lead to incorrect validations if used alone.

To ensure accuracy, you must perform a round-trip check. First, convert the IP to an integer with `ip2long()`, then convert it back to a dotted-quad string with `long2ip()` and compare it to the original input.

This process is faster than regular expression matching and effectively catches alternate notations. You should only use this method when you explicitly need to disallow IPv6 addresses, as detailed in these validation methods.

function isIpv4Strict(string $ip): bool
{
    $long = ip2long($ip);
    return $long !== false && long2ip($long) === $ip;
}

Regex Validation with `preg_match`

Regular expressions are useful when you need to enforce a policy that built-in functions do not support. For example, you might want to forbid the use of "0" in any octet.

To do this, you write a finite, anchored expression and test the IP address against it with `preg_match`.

For IPv6, it is best to generate the pattern with an algorithm or use a library. Hand-crafting a full IPv6 regex is complex and prone to errors, as noted by Sling Academy.

const IPV4_STRICT =
    '/^(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)'
    . '(\.(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)){3}$/';

function isIpv4Regex(string $ip): bool
{
    return (bool)preg_match(IPV4_STRICT, $ip);
}

Challenges of IP Address Validation in PHP

While these PHP functions offer validation capabilities, they come with significant drawbacks. These issues can compromise security and create unreliable outcomes, which makes robust IP validation a complex task.

  • The behavior of `filter_var` with `FILTER_VALIDATE_IP` changes between PHP versions. A previously valid IP might fail validation after a minor update, which creates unpredictable results and makes the function's output hard to trust across different environments.
  • Attackers exploit alternate notations like octal or hexadecimal. These can bypass weak `preg_match` patterns or incorrect `filter_var` flags. The IP resolves differently at the socket layer, which subverts security logic like allow or deny lists.
  • The dual-stack reality of IPv4 and IPv6 complicates validation. Methods like `ip2long` only support IPv4, while comprehensive `preg_match` patterns for all IPv6 formats are complex to create and maintain, which leaves edge cases unvalidated.
  • Validation functions like `filter_var` and transport libraries can parse IPs differently. This divergence produces false positives or negatives. Attackers exploit these inconsistencies to bypass access controls or execute server-side request forgery attacks.

Validate IP Addresses with Abstract API
Protect your project from unwanted traffic. Learn to validate IP addresses in your PHP code.
Get started for free

How Abstract API Handles IP Address Validation in PHP

Abstract API addresses the core weaknesses of traditional validation methods by moving the complexity to a managed endpoint that uses constantly updated datasets.

  • It checks an IP address for a history of abuse and flags it accordingly.
  • It detects if the address belongs to anonymity infrastructure like a VPN, proxy, or TOR network.
  • It provides corporate context, which includes the ASN, company name, and connection type.
  • It eliminates the need for local data maintenance through daily updates from proprietary threat-feeds and location datasets.

How to Set Up Abstract API in Your Project

Once you understand Abstract’s capabilities, the addition of its IP address validation API to your project is simple.

  • Sign up at abstractapi.com and create an IP Intelligence application to get your API key.
  • Use composer to require guzzlehttp/guzzle, or use any PSR-18 client already in your stack.
  • Add an environment variable: ABSTRACT_IP_KEY=YOUR_API_KEY. You should never hard-code secrets.
  • Create a thin wrapper class that injects the HTTP client and reads the key from the environment.
  • Call the GET endpoint at https://ip-intelligence.abstractapi.com/v1/ with your API key and the target IP address.
  • Cache non-security fields if latency is a concern. You should fetch security flags fresh for each request.

Sample IP Address Validation Implementation with Abstract API

The PHP code below uses a Guzzle client to send a GET request to the Abstract API endpoint. It passes the API key from an environment variable and the IP address "8.8.8.8" as query parameters. The code then decodes the JSON response into a PHP associative array.

$client = new \GuzzleHttp\Client();
$response = $client->get('https://ip-intelligence.abstractapi.com/v1/', [
    'query' => [
        'api_key'    => getenv('ABSTRACT_IP_KEY'),
        'ip_address' => '8.8.8.8'
    ],
    'timeout' => 2.0
]);
$data = json_decode($response->getBody(), true);

if ($data['security']['is_abuse'] || $data['security']['is_proxy']) {
    throw new \RuntimeException('High-risk IP rejected');
}

After it receives the data, the script checks the security flags. If the API reports that the IP address has a history of abuse or is a proxy, the code throws an exception to reject the request. Below is an abridged sample of the data the API returns for a valid IP address.

{
  "ip_address": "8.8.8.8",
  "security": {
    "is_vpn": false,
    "is_proxy": false,
    "is_tor": false,
    "is_hosting": false,
    "is_abuse": false
  },
  "asn": {
    "asn": 15169,
    "name": "Google LLC",
    "domain": "google.com",
    "type": "business"
  },
  "location": {
    "country": "United States",
    "country_code": "US",
    "region": "California",
    "city": "Mountain View",
    "postal_code": "94043",
    "latitude": 37.386,
    "longitude": -122.0838
  },
  "timezone": {
    "name": "America/Los_Angeles",
    "utc_offset": "-07:00",
    "local_time": "2025-07-19T05:12:54-07:00",
    "is_dst": true
  }
}

In this response, the security flags are all "false", which confirms the address is not a VPN, proxy, or TOR exit and has no abuse history. The ASN data confirms Google owns the IP. The location and timezone fields allow for geo-personalization and compliance decisions. These enriched fields arrive in one request and can drive risk scores or content localization without the maintenance of local IP data.

Final Thoughts

Traditional validation methods often fail because they use out-of-date data and cannot detect threats from anonymous networks. Abstract API overcomes these issues with a managed endpoint fed by current datasets. This provides a complete picture of an IP's reputation. Consider an account on Abstract API to get your free API key and reliably validate user IPs.

Validate IP Addresses with Abstract API
Validate user IP addresses in PHP to protect your application from malicious activity and abuse.
Get started for free

Related Articles

Phone Validation
key now
Get your free
stars rating
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required