PHP5 min setupBeginner

Block Fake Phone Numbers in PHP Registration Forms

Prevent spam accounts by validating phone numbers during user registration. This recipe shows you how to integrate Phone Validator API into your PHP registration flow.

The Problem

Spam bots and fake users register with invalid phone numbers like "555-0000" or "1234567890". This clogs your database, skews analytics, and wastes resources on fake accounts.

The Solution

Use Phone Validator API to check if the phone number is valid before creating the account. The API returns detailed information including format, carrier, and whether the number is real.

1Get Your API Key

Sign up on RapidAPI and get your API key for Phone Validator:

Get Free API Key →

2Add Validation to Your Registration Form

register.php

<?php
// Registration form handler
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $phone = $_POST['phone'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    
    // Validate phone number with API
    $isValidPhone = validatePhoneNumber($phone);
    
    if (!$isValidPhone) {
        die(json_encode([
            'success' => false,
            'message' => 'Invalid phone number. Please provide a valid number.'
        ]));
    }
    
    // Continue with registration
    // ... (save to database, send verification email, etc.)
    
    echo json_encode([
        'success' => true,
        'message' => 'Registration successful!'
    ]);
}

function validatePhoneNumber($phone) {
    $apiKey = 'YOUR_RAPIDAPI_KEY_HERE'; // Replace with your key
    
    $curl = curl_init();
    
    curl_setopt_array($curl, [
        CURLOPT_URL => "https://phone-validator7.p.rapidapi.com/validate?phone=" 
                       . urlencode($phone),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "GET",
        CURLOPT_HTTPHEADER => [
            "X-RapidAPI-Host: phone-validator7.p.rapidapi.com",
            "X-RapidAPI-Key: " . $apiKey
        ],
    ]);
    
    $response = curl_exec($curl);
    $err = curl_error($curl);
    
    curl_close($curl);
    
    if ($err) {
        // Log error and allow registration (fail open)
        error_log("Phone validation error: " . $err);
        return true; // Don't block registration on API errors
    }
    
    $data = json_decode($response, true);
    
    // Check if phone is valid
    if (isset($data['valid']) && $data['valid'] === true) {
        return true;
    }
    
    return false;
}
?>

3Create the HTML Form

registration-form.html

<form id="registrationForm" method="POST" action="register.php">
    <div class="form-group">
        <label for="email">Email</label>
        <input type="email" id="email" name="email" required>
    </div>
    
    <div class="form-group">
        <label for="phone">Phone Number</label>
        <input type="tel" id="phone" name="phone" 
               placeholder="+1 555-123-4567" required>
        <small>Include country code (e.g., +1 for USA)</small>
    </div>
    
    <div class="form-group">
        <label for="password">Password</label>
        <input type="password" id="password" name="password" required>
    </div>
    
    <button type="submit">Register</button>
</form>

<script>
document.getElementById('registrationForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    
    fetch('register.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('Registration successful!');
            window.location.href = '/dashboard';
        } else {
            alert(data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Registration failed. Please try again.');
    });
});
</script>

What the API Returns

Example Response

Valid Phone Number:

{
  "valid": true,
  "number": "+15555551234",
  "local_format": "(555) 555-1234",
  "international_format": "+1 555-555-1234",
  "country_code": "US",
  "country_name": "United States",
  "location": "California",
  "carrier": "Verizon",
  "line_type": "mobile"
}

Invalid Phone Number:

{
  "valid": false,
  "error": "Invalid phone number format"
}

Advanced Tips

Block Specific Phone Types

You can also block specific types like VOIP or landlines:

// Only allow mobile numbers
if ($data['line_type'] !== 'mobile') {
    return false; // Block VOIP, landline, etc.
}

Cache API Results

Cache validation results to reduce API calls:

// Check cache first
$cacheKey = 'phone_' . md5($phone);
$cached = apcu_fetch($cacheKey);

if ($cached !== false) {
    return $cached;
}

// Validate with API
$isValid = validatePhoneNumber($phone);

// Cache for 7 days
apcu_store($cacheKey, $isValid, 604800);

return $isValid;

Log Blocked Attempts

Track spam attempts for analytics:

if (!$isValidPhone) {
    // Log to database or file
    error_log(sprintf(
        "Blocked registration attempt with invalid phone: %s from IP: %s",
        $phone,
        $_SERVER['REMOTE_ADDR']
    ));
}

Next Steps

  • 1.Get your free API key from RapidAPI
  • 2.Copy the code above and replace YOUR_RAPIDAPI_KEY_HERE
  • 3.Test with valid and invalid phone numbers
  • 4.Monitor your spam reduction in analytics

Ready to Implement?

Get your free API key and start blocking fake phone numbers today.

Get Free API Key →