Example PHP Script - Print Uptime

Here is an example PHP script which uses the API to print the gateway's uptime. The completed script is available as an attachment on this page. Many thanks to the kind anonymous author for allowing me to post this example!

Requirements

  • PHP

  • cURL

Code

Download the full source code. -

  1. Start a new PHP script. Configure the script for your particular gateway

    <?     $GATEWAY_IP = 'CHANGEME';     $USERNAME = 'admin';     $PASSWORD = 'admin';       $ch = curl_init();       $fields = array(         'admin_uid'      => $USERNAME,         'admin_password' => $PASSWORD     );
  2. Log in to your gateway. This will save your authentication cookies in memory so that subsequent calls will be allowed.

    curl_setopt($ch, CURLOPT_URL, "https://$GATEWAY_IP/admin/main.html"); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_COOKIEFILE, ''); $result = curl_exec($ch);   if ($result === false) {     $error = curl_error($ch);     curl_close($ch);       die("Login failed: $error"); }   if (preg_match("/Welcome,\\s+$USERNAME/i", $result) == 0     || preg_match("/Log Out/i", $result) == 0) {     curl_close($ch);     die("Login Failed!"); }
  3. Build a call to the gateway.list method to get information about the gateway.

        $request = array(         'request' => array(             'method'     => 'gateway_list',             'parameters' => array()         )     );       $string = json_encode($request, JSON_FORCE_OBJECT);     $fields = array(         'request' => $string     );       curl_setopt($ch, CURLOPT_URL, "https://$GATEWAY_IP/json");     curl_setopt($ch, CURLOPT_POST, 1);     curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);     curl_setopt($ch, CURLOPT_HEADER, false);     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);       $result = curl_exec($ch);       if ($result === false) {         $error = curl_error($ch);         curl_close($ch);           die("Request failed: $error");     }       curl_close($ch);       $response = json_decode($result);     $response_object = json_decode($response->response->result);     print $response_object->gateway->model_name; print "\n";     print "Uptime "; print $response_object->gateway->uptime; print "\n"; ?>

 

Return to Documentation Home I Return to Sangoma Support