Phone Number API

There are two ways to buy a new Twilio number: the easy way, and the advanced way. This HowTo demonstrates the easy way. For the more advanced way, see the HowTo titled "Search For and Buy a New Twilio Number".

The easy way to buy a new Twilio phone number lets you grab a number at random within a given area code, assuming there is at least one number in that area code in Twilio's inventory.


This HowTo demonstrates a simple way to provision a new Twilio number using just the REST API's IncomingPhoneNumbers resource.


We set up a simple form that lets a user buy a new Twilio number by entering an area code. When the user clicks "BUY", we make an HTTP POST request to Twilio to provision the number.


  • 1

    • We first display a simple form to the user instructing him or her to enter a US area code

      • howtos/buy-a-number/buy-a-number.php
        <?php if(empty($_POST['submit'])): ?>
        		<title>Buy a Twilio number by area code</title>
        		<h3>Buy a Twilio number by area code</h3>
        		<?php if(!empty($_GET['msg'])): ?> 
        			<p class="msg"><?php echo htmlspecialchars($_GET['msg']); ?></p>
        		<?php endif;?>
        		<form method="POST">
        			<label>Enter a US area code: </label>
        			<input type="text" size="3" name="area_code"/>
        			<input type="submit" name="submit" value="BUY"/>
        <?php endif; ?>
  • 2

    • Upon receiving the user's area code selection, we POST the area code to the IncomingPhoneNumbers resource, and report back either success or failure.

      • howtos/buy-a-number/buy-a-number.php
        	require "Services/Twilio.php";
        	if (!empty($_POST['submit']) && $_POST['submit'] == 'BUY') {
        		/* Set our AccountSid and AuthToken */
        		/* AreaCode requested to buy */
        		$areaCode = trim($_POST['area_code']);
        		/* Instantiate a new Twilio Rest Client */
        		$client = new Services_Twilio($accountSid, $authToken);
        		try {
        			// POST the AreaCode to buy in to the IncomingPhoneNumbers resource
        			$number = $client->account->incoming_phone_numbers->create(array(
        				"AreaCode" => $areaCode,
        			$msg = urlencode(
        				"You are now the proud owner of {$number->phone_number}");
        			header("Location: ?msg=$msg");
        		} catch (Exception $e) {
        			// If we weren't able to process the request successfully, return
        			// the error back to the user
        			$err = urlencode(
        				"Error processing request for $areaCode: {$e->getMessage()}");
        			header("Location: ?msg=$err");