M/Monit php curl connection

106 Views Asked by At

Iam trying to write a PHP script to use the M/Monit API

https://mmonit.com/documentation/http-api/static/Examples/cURL.html

I am having a problem converting the command line script to run using PHP CURL

curl -c ~/.mmonit/cookie \
 http://127.0.0.1:8080/index.csp

curl -b ~/.mmonit/cookie \
 -d z_username=admin \
 -d z_password=swordfish \
 -d z_csrf_protection=off \
 http://127.0.0.1:8080/z_security_check

curl -b ~/.mmonit/cookie \
 http://127.0.0.1:8080/api/1/status/hosts/list

This is what I have

$url1 = "http://127.0.0.1:8080/index.csp";
$url2 = "http://127.0.0.1:8080/z_security_check";
$url3 = "http://127.0.0.1:8080/api/1/status/hosts/list";
$dataa["z_username"] = "admin";
$dataa["z_password"] = "swordfish";
$dataa["z_csrf_protection"] = "off";
$headers[] = 'Content-type: application/json';
$data = json_encode($dataa);


//STEP 1 Set Cookie
$ch = curl_init($url1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, '/tmp/cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, '/tmp/cookies.txt');

$response1 = curl_exec($ch);
curl_close($ch);
print_r($response1);

//Step 2 Send Auth
$ch = curl_init($url2);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, '/tmp/cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, '/tmp/cookies.txt');

$response2 = curl_exec($ch);
curl_close($ch);
print_r($response2);


//Step 3 Get data
$ch = curl_init($url3);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, '/tmp/cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, '/tmp/cookies.txt');

$response3 = curl_exec($ch);
curl_close($ch);
print_r($response3);

I get no data just the login form returned each time

I have tried set POST on and off in step 3

Am I correctly using Curl

Also the cookie file in /tmp/cookies.txt is being created correctly

1

There are 1 best solutions below

0
Liam On

Found the problem

I needed to set headers as this

$headers[] = 'Content-Type: application/x-www-form-urlencoded';