Asterisk: Initiate a call from extension by PHP script

If you have an asterisk PBX and some kind of internal web-based system like intranet or CRM with a contacts that your team need to call from time to time, there is an easy way to allow users fast dial those contact by linking a telephone number on a web page with a script that will call Asterisk and instruct it to dial first the user extension, and then connect him to the contact number.

The example code, that was originally taken from here and slightly modified looks like this:

# ip address that asterisk is on.
$strHost = "127.0.0.1"; 

# asterisk manager username and password
$strUser = "admin";
$strSecret = "secret_password"; 

# specify the channel (extension) you want to receive the call requests with
# e.g. SIP/XXX, IAX2/XXXX, ZAP/XXXX, etc
$strChannel = $_REQUEST['exten'];
$strContext = "from-internal";

$number = strtolower($_REQUEST['number']);
$strCallerId = $number;

#specify the amount of time you want to try calling the specified channel before hangin up
$strWaitTime = "30";

#specify the priority you wish to place on making this call
$strPriority = "1";

# validation
$valNumber = '/^\d+$/';
$valExt = '/^(SIP|IAX2|ZAP)\/\d+$/';

if (!preg_match($valNumber, $number)) {
    print "The number is incorrect, should match '$valNumber' pattern\n";
    exit();
}
if (!preg_match($valExt, $strChannel)) {
    print "The extension is incorrect, should match '$valExt' pattern\n";
    exit;
}

$errno=0 ;
$errstr=0 ;
$oSocket = fsockopen ($strHost, 5038, $errno, $errstr, 20);

if (!$oSocket) {
    echo "$errstr ($errno)<br>\n";
    exit();
}

fputs($oSocket, "Action: login\r\n");
fputs($oSocket, "Events: off\r\n");
fputs($oSocket, "Username: $strUser\r\n");
fputs($oSocket, "Secret: $strSecret\r\n\r\n");
fputs($oSocket, "Action: originate\r\n");
fputs($oSocket, "Channel: $strChannel\r\n");
fputs($oSocket, "WaitTime: $strWaitTime\r\n");
fputs($oSocket, "CallerId: $strCallerId\r\n");
fputs($oSocket, "Exten: $number\r\n");
fputs($oSocket, "Context: $strContext\r\n");
fputs($oSocket, "Priority: $strPriority\r\n\r\n");
fputs($oSocket, "Action: Logoff\r\n\r\n");
sleep(2);
fclose($oSocket);

echo "Extension $strChannel should be calling $number." ;

So, for example, if you put this code on the asterisk server in a web root as call.php and then call http://<your_asterisk_ip_address>/call.php?exten=SIP/737&number=77777777, your asterisk will attempt to connect extension 737 with number 77777777.

Leave a Reply