I’m using this php script to get a list of the the extensions from a remote Freepbx server but it just dies. Likely because the response i’m getting is: “Asterisk Call Manager/2.8.0” but if I uncomment that line out it spins it’s wheels what am I doing wrong?
This is being tested on FreePBX 13.0.195.26, AMI user exists and I can telnet to the server. The response I get from telnet upon login is
“Response: Success
Message: Authentication accepted”
Any help would be greatly appreciated.
<?php
// Define the host and port of the Asterisk server
$host = "192.168.1.110"; // remote Asterisk server IP address
$username = "myamiuser";
$password = "myamipassword";
$port = "5038";
// Connect to the Asterisk server
$fp = fsockopen($host, $port, $errno, $errstr, 30);
if (!$fp) {
echo "Could not connect to the Asterisk server: $errstr ($errno)\n";
exit;
}
// Login to the Asterisk Manager Interface (AMI)
$login = "Action: login\r\n";
$login .= "Username: $username\r\n";
$login .= "Secret: $password\r\n";
$login .= "\r\n";
fwrite($fp, $login);
// Check the login response
$login_response = fgets($fp);
if (trim($login_response) != "Response: Success") {
//if(trim($login_response) != "Asterisk Call Manager/2.8.0"){
echo "Could not log in to the Asterisk Manager Interface: $login_response\n";
fclose($fp);
exit;
//}
}
// Get a list of all extensions
$extension_list_command = "Action: ExtensionStateList\r\n\r\n";
fwrite($fp, $extension_list_command);
// Initialize an array to store the extensions
$extensions = array();
// Parse the response to get the extensions
while (!feof($fp)) {
$line = fgets($fp);
if (substr($line, 0, 11) == "Event: ExtensionState") {
// Extract the extension number and status from the response
$extension_number = trim(substr($line, strpos($line, "Extension:") + 10));
$status = trim(substr(fgets($fp), strpos(fgets($fp), "Status:") + 7));
// Add the extension number and status to the array
$extensions[] = array("number" => $extension_number, "status" => $status);
}
}
// Close the connection to the Asterisk server
fclose($fp);
// Print the list of extensions
echo "List of extensions:\n";
foreach ($extensions as $extension) {
echo "Extension: " . $extension['number'] . " Status: " . $extension['status'] . "\n";
}