Skip to content

Instantly share code, notes, and snippets.

@mattpr
Last active August 28, 2017 14:45
Show Gist options
  • Save mattpr/9ed8f97f0a7a184c17da99a3d2463e7a to your computer and use it in GitHub Desktop.
Save mattpr/9ed8f97f0a7a184c17da99a3d2463e7a to your computer and use it in GitHub Desktop.
PHP implementation of sip2pstn which allows outgoing calls via Twilio from your SIP registered phone. Within Twilio, programmable voice, SIP Domain, you should point the Voice URL at this file (on your server).
<?php
// should be configured in twilio under Programmable Voice > SIP Domain > Voice Config
// http://yourdomain.com/sip2pstn.php?callerId=%2B<yourTwilioNumberIncludingCountryCode>
// to adapt this for other countries
// - change the +44 to your own country code and
// - change the ringTone from 'uk' to your country (us, de, etc)
// this is not currently setup for USA 10 digit dialing (ie you should dial 001 or +1 or 1 before the 10 digit US number.
$localCountryCode="+44";
$localRingTone="uk";
$from = $_REQUEST['callerId']; // one of your twilio numbers
$to=$_REQUEST['To'];
if (empty($to)) {
header("HTTP/1.1 500 Internal Server Error");
echo 'Missing "To" parameter.';
die;
}
// extract To number from request
preg_match('/^sip:([+]?[0-9]{10,14})@/', $to, $number_matches, PREG_OFFSET_CAPTURE);
if (sizeof($number_matches) != 2) {
header("HTTP/1.1 500 Internal Server Error");
die;
}
else if ($number_matches[1][0][0] == '0') {
if ($number_matches[1][0][1] == '0') { // 00 prefix, replace with +
$number = '+' . substr($number_matches[1][0], 2);
}
else { // 0 prefix, replace 0 with +CountryCode
$number = $localCountryCode . substr($number_matches[1][0], 1);
}
}
else if ($number_matches[1][0][0] == '+') { // already formatted +number
$number = $number_matches[1][0];
}
else { // starts with 1-9, prepend +
$number = '+' . $number_matches[1][0];
}
header("content-type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<Response>
<Dial ringTone="<?=$localRingTone?>" answerOnBridge="true" callerId="<?=$from?>" record="do-not-record">
<Number><?=$number?></Number>
</Dial>
</Response>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment