[Asterisk-Users] Asterisk Manager PHP Class

Chris Jensen cjensen at uninets.net
Thu Nov 4 13:31:33 MST 2004


In the event that this is remotely helpful to anyone, I would like to
share the first class I have written for PHP.  If its ugly, its because
I don't pretend to know what I am doing... :P Good luck.


asterisk.class.php:
<?
//**********************************************************************
**//
/*
Setup asterisk manager class.
*/
class asterisk{
        var $host;
        var $port;
        var $a;

        function asterisk($host,$port) {
                $this->host=$host;
                $this->port=$port;
        }

        function connect() {
                $this->socket = fsockopen($this->host,$this->port,
$errno, $errstr, 30);
        if (empty($this->socket) || $this->socket==false) {
                $this->error=array("errorno"=>-1, "errstr"=>$errstr);
                return false;
        } else {
        return true;
                }
        }

        function login($user, $pass) {
                fputs($this->socket, "Action: Login\r\n");
                fputs($this->socket, "UserName: " . $user . "\r\n");
                fputs($this->socket, "Secret: " . $pass . "\r\n\r\n");
        }

        function logout() {
                fputs($this->socket, "Action: Logoff\r\n\r\n");
        }

        function sendc($cmd) {
                fputs($this->socket, "Action: Command\r\n");
                fputs($this->socket, "Command: " . $cmd . "\r\n\r\n");
        }

        function read() {
                while (!feof($this->socket)) {
                        $retstr .= fread($this->socket, 8192);
                }
                fclose($this->socket);
                return $retstr;
        }

        function skipline($skip) {
                if(!$skip) { $skip = 0; }
                while($skip!=0) {
                fgets($this->socket, 1024);
                $skip-=1;
                }
        }
}
//**********************************************************************
**//
?>

manager.php:
<?php
include("asterisk.class.php");

if(!isset($_POST['cmd'])) {
$cmd = "sip show peers";
} else {
$cmd = $_POST['cmd'];
}

writeform();
$a=new asterisk('127.0.0.1',5038);
$a->connect();
$a->login('username','password');
$a->sendc($cmd);
$a->logout();
$a->skipline(6);
$out = $a->read();
print "<PRE>" . $out;
//**********************************************************************
**//
/*
The form.
*/
function writeform()
{
print <<<EndForm
<form action="" method="post">
  <p> Enter Command:
    <input type="text" name="cmd">
    <input type="submit" name="Submit" value="submit"><BR>
    </p>
  </form>
EndForm;
}
?>




More information about the asterisk-users mailing list