Working to allow developers to easily interface with traditional communication methods including phone calls and text messages, Twilio provides a simple API service for us to send a text message to a specific number. We can first start with creating another <form>
element based on the original search box, except this element will appear only if the $s
variable is not empty:
share.php
<? if ($s != "") { ?>
<form action="send.php" method="POST">
<input name="search" type="hidden" value="<?= $s ?>">
<div class="input-group mb-3">
<input name="number" type="text" class="form-control" required placeholder="Recipient Number">
<div class="input-group-append">
<button class="btn btn-primary" type="submit">Send</button>
</div>
</div>
</form>
<? } ?>
While loosely based on the previous search.php
, the above snippet provides the following important distinctions:
<form>
shows up only if $s
is not empty<form>
now submits to the currently nonexistent send.php
page, using POST
method instead of GET
<input>
element now has new name
and placeholder
attributes, and requires a value to proceed<input>
element called "search" is added to pass the current search query to send.php
Using the POST
method discussed in cURL article, we can construct a POST call to the Twilio server. As Twilio APIs can be cumbersome to navigate at first, one can use the following sample code:
send.php
<?
$phone = $_POST["number"];
$body = "Check out this image list: http://ocad.ckprototype.com/public/wk4-ck/index.php?search=".$_POST["search"];
$from = "+13656065277";
$data = "To=".$phone."&From=".$from."&Body=$body";
$headers = array(
'Content-Type: application/x-www-form-urlencoded'
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://api.twilio.com/2010-04-01/Accounts/ACb7e63b5c8d88a4c6cd7d2d155ad355ea/Messages.json');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_USERPWD, 'ACb7e63b5c8d88a4c6cd7d2d155ad355ea' . ':' . 'f88467487801429e8288fb24aaf1e0d3');
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($curl);
curl_close();
header("Location: index.php?search=".$_POST["search"]);
?>
We are making the necessary call to Twilio using the following steps:
phone
and body
)$data
variableFrom
phone number, along with destination URL and user-password combo, have been created specifically for this tutorial.
If successful, the contents of the above body
variable will be sent to the recipient's cell phone.