PHP can validate phone numbers two ways. A regex check with preg_match() confirms the format, but not whether the number is real. To validate activity and carrier assignment, use Trestle’s Phone Validation API.
Ensuring the accuracy and validity of user-submitted phone numbers is crucial for maintaining data quality and improving user experience. PHP, being a versatile server-side scripting language, provides a solid foundation for implementing phone number validation. However, to enhance the validation process and gain deeper insights into phone numbers, integrating with Trestle’s Phone Validation API can significantly elevate your application’s capabilities.
In this guide, we’ll explore how to implement phone number validation using PHP, and then show how to enhance it with Trestle’s Phone Validation API.
Part 1: Basic Phone Validation with PHP #
PHP allows us to perform server-side validation of phone numbers. Here’s a basic example of how you might implement phone number validation using PHP and a simple regex pattern:
<?php
function validatePhoneNumber($phoneNumber) {
// Basic regex for phone number validation
$phoneRegex = '/^\+?[1-9]\d{1,14}$/';
return preg_match($phoneRegex, $phoneNumber) === 1;
}
// Example usage
$phoneNumber = '+12345678901';
if (validatePhoneNumber($phoneNumber)) {
echo "Valid phone number";
} else {
echo "Invalid phone number";
}
?>This basic implementation checks if the input matches a basic phone number format. However, this approach has limitations:
- It only checks the format, not whether the number is actually in service.
- It doesn’t provide any additional information about the phone number.
- It may not catch all valid or invalid formats.
Part 2: Enhancing Validation with Trestle’s API #
To overcome these limitations and provide a more robust validation solution, we can integrate Phone Validation API. This API not only validates the phone number format but also provides valuable additional information. You can view the full request and response schema in the API Documentation.
Here’s how we can enhance our PHP script to use Trestle’s API:
<?php
function validatePhoneWithTrestle($phoneNumber, $apiKey) {
// Build the API URL with the phone number parameter, ensuring it is URL-encoded
$url = "https://api.trestleiq.com/3.0/phone_intel?phone=" . urlencode($phoneNumber);
// Initialize a cURL session
$curl = curl_init($url);
// Set cURL options
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Return the response as a string
curl_setopt($curl, CURLOPT_HTTPHEADER, [ // Set headers for the API request
"x-api-key: $apiKey", // API key for authentication
"Accept: application/json" // Expect a JSON response
]);
// Execute the cURL request and capture the response
$response = curl_exec($curl);
// Check for cURL errors
$err = curl_error($curl);
// Close the cURL session
curl_close($curl);
// Handle errors if any occurred during the cURL request
if ($err) {
return "cURL Error #: " . $err;
} else {
// Decode the JSON response into an associative array
return json_decode($response, true);
}
}
// Example usage
// API key for accessing Trestle's Phone Validation API
$apiKey = 'your_api_key_here';
// Phone number to validate
$phoneNumber = '+12345678901';
// Call the validation function and store the result
$result = validatePhoneWithTrestle($phoneNumber, $apiKey);
// Check if the result contains a valid response
if (isset($result['is_valid'])) {
// Output the validation details
echo "Is Valid: " . ($result['is_valid'] ? 'Yes' : 'No') . "\n";
echo "Activity Score: " . $result['activity_score'] . "\n";
echo "Line Type: " . $result['line_type'] . "\n";
echo "Carrier: " . $result['carrier'] . "\n";
} else {
// Handle errors during validation
echo "Error: Unable to validate phone number";
}
?>The Power of PHP + Trestle’s API for Phone Validation #
By integrating Trestle’s API with our PHP script, you can significantly enhance your phone validation capabilities:
- Comprehensive Validation: Beyond just format checking, we now verify if the number is actually assigned to a carrier.
- Phone Activity Score: Phone Validation API provides a Phone Activity Score, indicating the likelihood that the number is currently in use.
- Line Type Information: We can determine whether the number is a landline, mobile, fixed or non-fixed VoIP, etc.
- Carrier Details: The API provides information about the carrier associated with the number.
This enhanced validation process provides several benefits:
- Improved Data Quality: By validating the format and status of the phone number, you can ensure higher quality data in your system.
- Better User Experience: You can provide more detailed feedback to users about their input.
- Informed Decision Making: The additional data (like line type and carrier) can inform your business processes and communication strategies.
- Fraud Prevention: Identifying numbers with low activity scores can help in fraud detection efforts.
Best Practices for Implementation #
When implementing this enhanced validation in your PHP applications, consider the following best practices:
- Error Handling: Implement robust error handling to manage API errors gracefully and provide meaningful feedback to users.
<?php
function validatePhoneWithTrestle($phoneNumber, $apiKey) {
$url = "https://api.trestleiq.com/3.0/phone_intel?phone=" . urlencode($phoneNumber);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
"x-api-key: $apiKey",
"Accept: application/json"
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
// Throw an exception if a cURL error occurs
if ($err) {
throw new Exception("cURL Error #: " . $err);
}
// Decode the JSON response and check for errors
$result = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception("JSON decoding error: " . json_last_error_msg());
}
return $result;
}
// Example usage with exception handling
try {
$result = validatePhoneWithTrestle($phoneNumber, $apiKey);
// Process the API result
} catch (Exception $e) {
// Handle and display errors
echo "Error: " . $e->getMessage();
}
?>2. Rate Limiting: Implement rate limiting to ensure you don’t exceed Trestle’s API usage limits.
<?php
/**
* A rate limiter to control the number of API requests per second.
*/
class RateLimiter {
private $lastRequestTime = 0; // Timestamp of the last API request
private $requestsPerSecond; // Allowed number of requests per second
public function __construct($requestsPerSecond = 5) {
$this->requestsPerSecond = $requestsPerSecond;
}
/**
* Waits if the next request violates the rate limit.
*/
public function wait() {
$currentTime = microtime(true);
$timeToWait = (1 / $this->requestsPerSecond) - ($currentTime - $this->lastRequestTime);
if ($timeToWait > 0) {
usleep($timeToWait * 1000000); // Convert seconds to microseconds
}
$this->lastRequestTime = microtime(true);
}
}
// Usage example with rate limiting
$rateLimiter = new RateLimiter(5); // 5 requests per second
foreach ($phoneNumbers as $phoneNumber) {
$rateLimiter->wait(); // Ensure compliance with the rate limit
$result = validatePhoneWithTrestle($phoneNumber, $apiKey);
// Process the result here
}
?>3. Secure API Key Management: Use environment variables or a secure configuration file to manage your API key.
<?php
// Securely retrieve the Trestle API key from environment variables
$apiKey = getenv('TRESTLE_API_KEY');
// Check if the API key is not set
if (!$apiKey) {
throw new Exception("Trestle API key not found in environment variables");
}
// Validate the phone number with the retrieved API key
$result = validatePhoneWithTrestle($phoneNumber, $apiKey);
?>By implementing these best practices, you can create a more efficient, secure, and robust phone validation process in your PHP applications while maximizing the benefits of Trestle’s API.
Conclusion #
By combining PHP’s server-side capabilities with Trestle’s comprehensive Phone Validation API, you can create a robust, efficient phone validation system. This approach ensures the accuracy of phone numbers and provides valuable insights that can inform your business processes.
Whether you’re building a contact form, a user registration system, or managing a large customer database, this enhanced validation process can significantly improve the quality of your phone number data.
Ready to take your phone number validation to the next level? Sign up for a free Trestle account and start leveraging Phone Validation API with PHP today.
If you have any questions or need assistance with integration, feel free to contact us.
This user guide was written by Tyler Woodward, Technical Account Manager at Trestle.
Frequently Asked Questions #
What’s the difference between a valid phone number and an active one?
Format validation confirms a number is shaped correctly, but gives no indication as to whether anyone will actually pick up. Trestle’s is_valid field confirms the number is real and assigned, while our Phone Activity Score estimates how likely it is to be in use right now. A number can be valid but inactive.
How do I check a phone number’s format in PHP?
Use preg_match() with an E.164 pattern such as /^\+?[1-9]\d{1,14}$/. That confirms the number is shaped like a valid international number before you send it anywhere. Part 1 above has a working function.
What data does Trestle’s Phone Validation API return?
Each response includes whether the number is valid (is_valid), an activity_score from 0 to 100, the line_type (such as mobile, landline, or fixed or non-fixed VoIP), the carrier, and whether the line is prepaid. You can use these fields to score, route, or block a submission.