How to Validate Phone Numbers in PHP: From Regex to Reachability API

How to Validate Phone Numbers in PHP: From Regex to Reachability API

A complete PHP tutorial on validating phone numbers. Learn to format with libphonenumber-for-php and verify reachability via REST API.

To validate a phone number in PHP, first format the input using the giggsey/libphonenumber-for-php library to ensure it meets the E.164 standard. Because PHP libraries only verify syntax, you must then use a REST API like NumberChecker.AI to silently verify if your batch of numbers is reachable and registered on platforms like iMessage or Viber.


Prerequisites for PHP Phone Validation

Before writing the validation script, ensure your environment is set up for both local formatting and remote reachability checks. You will need a package manager to handle the local parsing library, and an API key to perform the actual reachability checks across 200+ countries.

Ensure you have the following ready:

  • PHP 7.4 or higher installed on your server or local environment.
  • Composer installed globally to require the giggsey/libphonenumber-for-php package.
  • A NumberChecker.AI API key for bulk batch verification.

Run the following command in your terminal to install the necessary formatting library:

composer require giggsey/libphonenumber-for-php

Step 1: The Limits of Basic PHP Regex and filter_var

Developers often start by using preg_match or filter_var to validate phone numbers. For example, a basic regex like preg_match("/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/", $phone) can enforce a specific pattern for a single region.

However, these basic PHP methods only check syntax and cannot confirm if a number is real. Relying solely on regex leads to false positives because it cannot verify reachability or platform registration. Furthermore, regex requires constant updating to accommodate changing international formats. While filter_var is excellent for standardizing integers or basic strings, it lacks the complex telecom rules required to accurately validate global dialing codes.


Step 2: Formatting with libphonenumber-for-php

To properly validate the syntax and format numbers to the E.164 standard, use the giggsey/libphonenumber-for-php library. The giggsey/libphonenumber-for-php library incorporates Google’s telecom metadata for length and country rules, ensuring your local syntax checks are as accurate as possible.

Failing to format numbers to E.164 before sending them to an API can cause validation errors. The following runnable PHP code demonstrates how to parse a batch of raw inputs and format them correctly:

require 'vendor/autoload.php';
use libphonenumber\PhoneNumberUtil;
use libphonenumber\PhoneNumberFormat;
use libphonenumber\NumberParseException;

$phoneUtil = PhoneNumberUtil::getInstance();
$rawNumbers = ['+12025550123', '07700900077', 'invalid_string'];
$formattedNumbers = [];

foreach ($rawNumbers as $number) {
    try {
        // Parse assuming US as default region if no country code is provided
        $proto = $phoneUtil->parse($number, "US");
        
        if ($phoneUtil->isValidNumber($proto)) {
            $formattedNumbers[] = $phoneUtil->format($proto, PhoneNumberFormat::E164);
        }
    } catch (NumberParseException $e) {
        // Silently skip or log invalid formats
        error_log("Error parsing $number: " . $e->getMessage());
    }
}

// $formattedNumbers now contains strictly E.164 formatted strings
print_r($formattedNumbers);

Step 3: Verifying Reachability via NumberChecker.AI REST API

Once your batch of numbers is formatted to E.164, the next step is verifying actual reachability. NumberChecker.AI provides a REST API for real-time, silent phone number reachability and platform verification. NumberChecker.AI supports 45+ platform detectors including iMessage, Viber, and Apple.

NumberChecker.AI is designed for bulk batch verification via CSV/TXT or REST API. For example, the iMessage checker accepts a minimum batch of 2,000 numbers. Crucially, NumberChecker.AI performs silent checks without notifying the account owner.

Here is a runnable PHP script using cURL to send your formatted batch to the API:

// Assuming $formattedNumbers contains valid E.164 numbers from Step 2
$apiKey = 'YOUR_API_KEY_HERE';
$apiUrl = 'https://api.numberchecker.ai/v1/imessage'; // Example endpoint

$payload = json_encode([
    'numbers' => $formattedNumbers
]);

$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $apiKey
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode === 200) {
    $results = json_decode($response, true);
    // Process the returned fields: Number, activated
    print_r($results);
} else {
    echo "API Request failed with HTTP status $httpCode";
}

Honest Limitations of Phone Validation

When building a validation workflow in PHP, it is important to understand the boundaries of the tools you are using.

  • Syntax vs. Reachability: PHP libraries can only confirm syntax, not reachability. A number can be perfectly formatted according to Google’s metadata but still be disconnected or inactive.
  • Formatting Requirements: API checks require valid E.164 formatting to function correctly. Raw user input must always be parsed locally first to avoid wasting API requests on malformed strings.
  • Batch Processing Focus: NumberChecker.AI is a batch processing tool, not a single-number lookup tool. Workflows should be designed to aggregate numbers and send them in bulk (e.g., batches of 1,000 to 2,000 minimum depending on the platform detector) rather than making individual HTTP requests for every single user registration.

Frequently Asked Questions (FAQ)

Can PHP natively verify if a phone number is active?

No, basic PHP methods like preg_match and filter_var only check syntax and cannot confirm if a number is real or active. You must use a third-party API to verify actual reachability.

What is the best regex for international phone numbers in PHP?

Relying solely on regex leads to false positives because it cannot verify reachability or platform registration, and requires constant updating for international formats. Instead of regex, use the giggsey/libphonenumber-for-php library for accurate syntax validation.

How do I format phone numbers to E.164 in PHP?

You can format phone numbers to the E.164 standard by installing the giggsey/libphonenumber-for-php library via Composer, parsing the raw input using PhoneNumberUtil::getInstance()->parse(), and then formatting it with PhoneNumberFormat::E164.

Get Started with NumberChecker.AI

Try NumberChecker.AI free — 1,000 checks on sign-up, no credit card required.

Ready to get started?

Try our WhatsApp number validation service and see the difference clean data makes.

Try Free Tool Contact Us