Validating phone numbers is a common requirement for ensuring data quality and reliable user communication in PHP. We will explore five distinct methods for this task, complete with working code, while also examining the pitfalls of traditional approaches and how Abstract API provides a more robust solution.
How to Implement Phone Number Validation in PHP
Here are a few common methods to validate phone numbers in PHP. Each approach offers a different way to check if a phone number format is correct.
Dedicated Regular Expression with preg_match
This approach uses a dedicated regular expression, or regex, to check phone numbers. A well-maintained pattern can enforce the E.164 standard, which formats numbers with a plus sign, country code, and subscriber number. The total length can be up to 15 digits.
The preg_match function in PHP executes the regex search. It returns true if the pattern matches the phone number string and false otherwise. This method gives you full control over the validation pattern and adds zero external dependencies to your project.
function isValidE164(string $n): bool {
return (bool)preg_match('/^\+?[1-9]\d{1,14}$/', $n);
}
filter_var with FILTER_VALIDATE_REGEXP
You can also use PHP's built-in filter_var function for validation. When paired with the FILTER_VALIDATE_REGEXP flag, it lets you use the same regex pattern while the core extension handles the input filter work.
A key feature of this function is its ability to work with filter_input(). This allows you to connect it directly into input-filter chains for POST, GET, or CLI data without extra wrapper code.
$ok = filter_var(
$n,
FILTER_VALIDATE_REGEXP,
['options' => ['regexp' => '/^\+?[1-9]\d{1,14}$/']]
);
Google libphonenumber Ports
For more advanced validation, you can use ports of Google's libphonenumber library. Popular PHP versions include giggsey/libphonenumber-for-php and brick/phonenumber, which you can install with Composer. These libraries contain the full metadata set that Google maintains.
This metadata provides several benefits for free.
- Length checks
- Country-specific rules
- Emergency and short-code detection
- Number format
- "Possible vs valid" logic
// Install with Composer: composer require giggsey/libphonenumber-for-php
// With giggsey/libphonenumber-for-php
$util = \libphonenumber\PhoneNumberUtil::getInstance();
$proto = $util->parse($n, $iso2); // e.g. “US”
$ok = $util->isValidNumber($proto);
// Or with Brick
$p = \Brick\PhoneNumber\PhoneNumber::parse($n, $iso2);
$ok = $p->isValidNumber();
Challenges of Implementing Phone Number Validation
These validation methods present several practical challenges. They struggle with diverse international formats, cannot confirm a number's live status, and rely on data that quickly becomes outdated.
- International number plans constantly evolve. A static regex used with preg_match or filter_var will miss valid cases. Even libphonenumber requires constant metadata updates to remain accurate across different regions and their unique formatting rules.
- A number can pass syntax checks with preg_match or libphonenumber yet be unreachable. These methods only confirm the format. They cannot detect disposable numbers, ported lines, or if the phone is active without external checks.
- Phone number data decays quickly as records turn invalid each month. The metadata libphonenumber caches in your codebase drifts from reality. This forces frequent package updates and production rollouts to maintain fresh data.
- Even mature libraries like libphonenumber fail on edge cases. Issues include confusion over maximum length, local-only numbers, and special territories. These problems force developers to patch rules or add custom logic on top of the library.
Validate Phone Numbers with Abstract API
Ensure accurate user data and improve communication by validating phone numbers in your PHP project.
Get started for free
How Abstract API Handles Phone Number Validation in PHP
Abstract API addresses the core weaknesses of traditional methods. It replaces brittle pattern checks with authoritative telco facts from a continuously updated data graph.
- It moves past simple format checks. The API confirms if a number is routable, who the carrier is, and its line type, like mobile, landline, or VOIP.
- The service removes the need for home-grown lookup tables that go stale. It relies on a data graph with current information on over 190 country number plans.
- It bypasses slow SMS round-trip checks. The API returns the line type in real time, so you can gate features for specific line types.
How to Add Abstract API to Your Dev Environment
Once you know Abstract’s capabilities, you can add its phone number validation API to your project with ease.
- Sign in at Abstract API, create a Phone Validation API project, and copy the key.
- In your project root, run:
composer require abstractapi/php-phone-validation
. - Require Composer’s autoloader if you have not already:
require 'vendor/autoload.php';
. - Configure the SDK once at boot with your API key.
use Abstractapi\PhoneValidation\AbstractPhoneValidation;
AbstractPhoneValidation::configure('YOUR_API_KEY');
Sample Phone Number Validation with Abstract API
The following code sends a phone number to the API. The API returns a detailed response object. This object contains the validation status, standardized formats, location, carrier, and line type.
<?php
use Abstractapi\PhoneValidation\AbstractPhoneValidation;
AbstractPhoneValidation::configure('YOUR_API_KEY');
$info = AbstractPhoneValidation::verify('+14152007986');
if (!$info->valid) {
throw new \RuntimeException('Invalid phone');
}
echo $info->format->international; // +14152007986
echo $info->carrier; // T-Mobile USA, Inc.
echo $info->line_type; // mobile
?>
Sample API Response
{
"phone": "14152007986",
"valid": true,
"format": {
"international": "+14152007986",
"local": "(415) 200-7986"
},
"country": {
"code": "US",
"name": "United States",
"prefix": "+1"
},
"location": "California",
"type": "mobile",
"carrier": "T-Mobile USA, Inc."
}
The response object provides key data points:
- valid: A true value indicates the number exists on an assignable range.
- format: This object provides both international and local presentation forms, useful for UI display.
- country/location: These fields allow geo-checks for fraud prevention or call routing.
- type/carrier: These fields let you branch logic. For example, you can disallow VOIP numbers or manage SMS costs per carrier.
Final Thoughts
Traditional validation methods often fail because they only check format or use outdated information. Abstract API bypasses these issues with a direct connection to a telecom data graph. It provides authoritative, real-time facts about a number’s validity, line type, and carrier. For reliable phone validation, create an account on Abstract API and get your free API key.
Validate Phone Numbers with Abstract API
Validate phone numbers in your PHP application to maintain clean data and prevent fake users.
Get started for free