How to Validate Phone Numbers Using PHP | Code Examples 2023

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

Phone number validation is an important aspect of many web applications, especially those that involve user input. It ensures that the phone number entered by the user is valid and can be used for various purposes like sending SMS, making phone calls, or storing in a database. In this article, we will explore different methods of validating phone numbers in PHP and the pros and cons of each method.

How to Validate Phone Numbers in PHP

In this article, we will explore three methods of validating phone numbers in PHP and discuss the best practices to follow to ensure your application is robust and reliable. We will also answer frequently asked questions about phone number validation to help you better understand this crucial aspect of web application development.

PHP Validate Phone Numbers Code Example

<?php
require_once 'vendor/autoload.php';
use libphonenumber\PhoneNumberUtil;
use libphonenumber\PhoneNumberFormat;

$phone_number = "123-456-7890";
$phoneUtil = PhoneNumberUtil::getInstance();
try {
    $numberProto = $phoneUtil->parse($phone_number, "US");
    if ($phoneUtil->isValidNumber($numberProto)) {
        echo "Valid US phone number";
    } else {
        echo "Invalid US phone number";
    }
} catch (\libphonenumber\NumberParseException $e) {
    echo "Invalid phone number";
}

//OUTPUT
//Invalid US phone number
?>

Article Highlights

  • Phone number validation is an important aspect of many web applications, especially those that involve user input.
  • Phone numbers can be categorized into two types – national and international. 
  • You can validate phone numbers in PHP using substr()preg_match(), or the libphonenumber library.
  • False positives can occur during phone number validation when a phone number appears to be valid based on the validation rules but is actually not a reachable or active number. 
  • Best practices for phone number validation in PHP include using established libraries, checking for common formatting patterns, and considering the possibility of false positives

Table of Contents

validate phone numbers php

Types of Phone Number Formats

Before we dive into the validation methods, it is essential to understand the different types of phone number formats. Phone numbers can be categorized into two types – national and international. 

National phone numbers are those that are valid within a particular country, whereas international phone numbers are those that are valid across different countries.

Different countries have different formats for phone numbers. For example, phone numbers in the United States are formatted as (XXX) XXX-XXXX, whereas in the United Kingdom, phone numbers are formatted as XXXX XXX XXXX. It is important to understand the phone number format of a particular country before validating it.

Validate Phone Numbers in PHP using substr()

When building a web application that requires phone number validation, one of the techniques you can use is the substr() function in PHP. This function allows you to extract a substring from a string, which can be useful for extracting specific characters from a phone number to validate it.

Example | Validate phone numbers in PHP using substr()

Here is an example of how to use substr() to validate a phone number in PHP.

<?php
function validatePhoneNumber($phoneNumber) {
   $phoneNumber = str_replace(' ', '', $phoneNumber);
   $phoneNumber = str_replace('-', '', $phoneNumber);
  
   if (strlen($phoneNumber) != 10) {
     return false;
   }
  
   $areaCode = substr($phoneNumber, 0, 3);
   $prefix = substr($phoneNumber, 3, 3);
   $lineNumber = substr($phoneNumber, 6, 4);
  
   if (!is_numeric($areaCode) || !is_numeric($prefix) || !is_numeric($lineNumber)) {
     return false;
   }
  
   return true;
 }


validatePhoneNumber('123-456-7890'); //true
?>

This function takes in a phone number as a parameter and first removes any spaces or dashes in the number. It then checks if the length of the phone number is exactly 10 digits, which is a typical requirement for US phone numbers.

Next, the function extracts the phone’s area code, prefix, and line number using substr(). It then checks if each of these components is numeric, which ensures that the phone number only contains digits and no other characters.

Finally, the function returns true if the phone number passes all of the validation checks and false otherwise.

Pros & Cons | Validate phone numbers in PHP using substr()

ProsCons
substr() is a built-in PHP function, so you do not need to install any external libraries or dependencies.substr() is not as powerful or flexible as other validation techniques, such as regular expressions or specialized libraries.
It is a relatively simple function, and the code is easy to understand.The validation rules are hard-coded into the function, so modifying or extending them may not be easy.

Limitations | Validate phone numbers in PHP using substr()

There are a few limitations to using substr() for phone number validation.

  • The validation rules are hard-coded into the function, so modifying or extending them may be difficult.
  • substr() can only extract a fixed number of characters from a string, which may not be sufficient for more complex phone number validation requirements.
  • The function assumes that the phone number is in a specific format (i.e., 10 digits), which may not be applicable to all types of phone numbers (e.g., international phone numbers).

Validate Phone Numbers in PHP using Regular Expressions

The first method of validating phone numbers is using regular expressions. Regular expressions are a powerful tool in PHP that allows you to search and manipulate text based on patterns.

 Regular expressions can define and validate a phone number’s format. PHP has the preg_match() function, which matches a string’s pattern with a regular expression.

Defining a pattern matching the number format to validate a phone number using regular expressions would be best. For example, the following regular expression matches a US phone number format: /^\+?1?\d{10}$/.

Example | Validate phone numbers in PHP using regular expressions

Here is an example code snippet that uses a regular expression to validate a US phone number:

<?php
$phone_number = "123-456-7890";
if(preg_match("/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/", $phone_number)) {
   echo "Valid US phone number";
} else {
   echo "Invalid US phone number";
}
?>

The regular expression /^[0-9]{3}-[0-9]{3}-[0-9]{4}$/ matches the pattern of a US phone number, which is three digits followed by a hyphen, then another three digits, and finally four digits.

Pros & Cons |  Validate phone numbers in PHP using regular expressions

ProsCons
Easy to implementCan be complex to create a robust pattern
Quick to executeNot as comprehensive as libphonenumber library-based validation
Can handle multiple phone number formatsLimited support for international phone number validation

Limitations |  Validate phone numbers in PHP using regular expressions

While regular expressions are a powerful tool for validating phone numbers in PHP, this approach has some limitations.

  1. Regular expressions can be complex and difficult to understand, especially for developers who are not familiar with them. This can lead to errors in the validation process.
  1. Regular expressions are not very flexible when validating different types of phone numbers. For example, you must create separate regular expressions for each country to validate phone numbers from different countries.
  1. Regular expressions can be difficult to maintain over time, especially if the phone number format changes or new formats are introduced. 
  1. Regular expressions can sometimes generate false positives, where a phone number is incorrectly validated as valid even though it is not.
  1. Regular expressions can also generate false negatives, where a phone number is incorrectly validated as invalid even though it is valid.

Overall, while regular expressions can be a useful tool for phone number validation in PHP, it is important to be aware of their limitations and consider other validation methods.

Validate Phone Numbers in PHP using the libphonenumber library

The second method of validating phone numbers is using the libphonenumber library. This open-source library developed by Google provides a comprehensive solution for validating and formatting phone numbers for different countries.

To use libphonenumber library-based validation in PHP, you must install the library using Composer. 

composer require giggsey/libphonenumber-for-php

Once installed, you can create a PhoneNumberUtil object and use its isValidNumber() method to validate a phone number.

Example | Validate phone numbers in PHP using libphonenumber

The following example code snippet uses libphonenumber to validate a US phone number.

<?php


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


$phone_number = "123-456-7890";
$phoneUtil = PhoneNumberUtil::getInstance();
try {
   $numberProto = $phoneUtil->parse($phone_number, "US");
   if ($phoneUtil->isValidNumber($numberProto)) {
       echo "Valid US phone number";
   } else {
       echo "Invalid US phone number";
   }
} catch (\libphonenumber\NumberParseException $e) {
   echo "Invalid phone number";
}


//OUTPUT
//Invalid US phone number
?>

The libphonenumber library which supports phone number parsing and validation for various countries, not just the US. By specifying the country code parameter in the parse method, it can validate phone numbers from different regions and formats.

Benefits | Validate phone numbers in PHP using libphonenumber

There are several benefits to using the libphonenumber library in PHP for validating phone numbers.

  1. The libphonenumber library is designed to handle a wide variety of phone number formats from around the world, including mobile, fixed-line, and toll-free numbers. It can also validate phone numbers with or without country codes, making it a flexible tool.
  1. It is highly accurate in validating phone numbers. It uses up-to-date phone number metadata to ensure that phone numbers are validated correctly. 
  1. The libphonenumber library is easy to integrate into your PHP application. It is available as a PHP library that you can download and use in your project. 
  1. The libphonenumber library includes functionality for formatting phone numbers in a localized way. This can be very useful if your application is used in multiple countries or languages.
  1. The libphonenumber library is regularly updated with new phone number formats and metadata. This helps to ensure that the library remains accurate and up-to-date over time.

Overall, the libphonenumber library is a powerful and flexible tool for validating phone numbers in PHP. It can help to ensure that your application only accepts valid phone numbers while also providing useful localization functionality.

Pros & Cons | Validate phone numbers in PHP using libphonenumber

ProsCons
Comprehensive solution for validating phone numbersCan be slower than regular expression-based validation
Supports international phone number validationMay require additional configuration and dependencies
Includes features such as formatting and parsing phone numbers

Limitation

While the libphonenumber library is a powerful tool for validating phone numbers in PHP, there are a few limitations to keep in mind.

  1. The libphonenumber library can be memory-intensive, especially when working with large datasets. This can be a concern if you are running your PHP application on a server with limited memory resources.
  1. While the libphonenumber library includes functionality for formatting phone numbers, it is not always possible to format phone numbers in exactly the way you want. This can be a concern if you need to present phone numbers in a specific format to your users.
  1. There may be some country-specific limitations or edge cases that the library cannot handle. It is important to thoroughly test the library with the phone numbers you need to validate to ensure that it works as expected.

Overall, the libphonenumber library is a powerful and flexible tool for validating phone numbers in PHP. However, it is important to keep these limitations in mind and to thoroughly test the library with your specific use case to ensure that it is the right tool for your needs.

Frequently Asked Questions

What are the common false positives while validating phone numbers in PHP?

False positives can occur during phone number validation when a phone number appears to be valid based on the validation rules but is actually not a reachable or active number. 

For example, a phone number may have the correct number of digits and format, but may no longer be in service or may not be assigned to anyone. 

Another example is when a phone number has the correct format but is not reachable due to network or technical issues.

Dealing with false positives during phone number validation can be challenging, but there are some steps that can be taken to minimize the risk of false positives:

  1. Implementing a phone number verification process. This process involves sending a verification code to the phone number and asking the user to enter the code to confirm that the phone number belongs to them.
  1. Use additional data sources, such as phone carrier databases or public records, to validate phone numbers and minimize the risk of false positives.
  1. By monitoring the usage of phone numbers, such as the number of calls or messages sent or received, you can detect and flag suspicious or inactive phone numbers.

Overall, it’s important to remember that phone number validation is not foolproof and may sometimes produce false positives. By using a combination of techniques and regularly monitoring phone number usage, you can minimize the risk of false positives and ensure that your phone number validation process is as accurate as possible.

What are some best practices for phone number validation in PHP?

Here are some best practices for phone number validation in PHP.

  1. Determine the specific requirements of your application and its users to choose the appropriate method of phone number validation.
  1. Use built-in functions and libraries for phone number validation, as these have already been tested and are likely to be more accurate than writing your own validation code.
  1. Regularly update your phone number validation methods to ensure accuracy, as country codes and phone number formats may change over time.
  1. Be flexible in handling additional characters and extensions, as users may enter them differently. Consider stripping these characters or extensions or treating them as separate fields.
  1. Provide clear and concise error messages to the user when a phone number is invalid, and allow them to correct the error.
  1. When storing phone numbers in a database, normalize the format to a standard format to make it easier to search and compare phone numbers.
  1. Consider providing a feature for users to verify their phone number, such as sending a verification code via SMS or voice call, to ensure that the phone number is valid and belongs to the user.
  1. Keep in mind any privacy or security concerns when handling phone numbers, such as encrypting phone numbers or ensuring that they are not visible to unauthorized users.

How to Validate Phone Numbers in PHP

There are three methods of validating phone numbers in PHP – substr(), regex validation, and the composer libphonenumber package. These methods have advantages and disadvantages, and the choice depends on the application’s specific requirements.

When validating phone numbers, it is essential to consider the phone number format and any additional characters or extensions. By following the best practices of phone number validation, you can ensure that your application is robust and reliable.

False positives are a common issue when validating phone numbers, as there are many variations in how phone numbers can be formatted. To minimize the chances of false positives, it is important to have a thorough understanding of the phone number formats that are valid in your target region, and to use the appropriate validation technique.

Best practices for phone number validation include using a combination of techniques, such as substr, regular expressions, and the libphonenumber library, to increase the validation accuracy. It is also recommended to provide clear error messages for users when a phone number is invalid, and to offer the option for users to manually enter their phone number if it cannot be validated automatically.

Hope you have enjoyed this article. Stay tuned for more at FuelingPHP.

Article series on Phone Communication

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.