Page 1 of 1

How can I call API using PHP?

Posted: Wed Jan 18, 2017 6:58 am
by dev.mellano
Dear All,

I wanna call API to get all the critical alerts by API.

Here is what I have tried:

Code: Select all

$user = 'myusername';
$pass = 'mypassword';
$url = "https://myserver/nagios/cgi-bin/statusjson.cgi?query=servicelist&details=true&servicestatus=critical";

$body = array('username' => $user, 'password' => $pass);
$body =  json_encode($body );
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url );
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

curl_setopt($ch, CURLOPT_POSTFIELDS, $body );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);


// grab URL and pass it to the browser, retaining the reply

$reply = curl_exec($ch);
print_r($reply);
$content_json = json_decode($reply);
print_r($content_json);die;

But I got nothing, Although I get the JSON data when I can the link from the browser after I put my credentials.

Can u help?

Best,
Dev

Re: How can I call API using PHP?

Posted: Wed Jan 18, 2017 10:38 am
by tmcdonald
This seems like more of a general PHP programming question. I would recommend printing every return code and variable value at each step to see where it is failing, but beyond that if it is an issue with the PHP functions (argument order, options, etc.) then that would be best asked on a programming forum.

Re: How can I call API using PHP?

Posted: Thu Jan 19, 2017 4:16 am
by dev.mellano
I tried the following code, and it is working fine with me, thank u :)

Code: Select all


<?php

$url= "https://username:password@servername/nagios/cgi-bin/statusjson.cgi?query=servicelist&servicestatus=critical&servicetimefield=lastupdate&starttime=01-19-2017";

$arrContextOptions=array(
    "ssl"=>array(
        "verify_peer"=>false,
        "verify_peer_name"=>false,
    ),
);  

$response = file_get_contents($url, false, stream_context_create($arrContextOptions));


$obj = json_decode($response);

var_dump( $obj); 

?>