I'm not a formally trained developer and I tend to just make things work for silly little projects, but I would like a few tips on how to condense some PHP code to be more compact and efficient.
At the moment, my code is as follows, it works and does what it's supposed to, but surely there's a better way to compose it:
<?php
function turnoff($j) {
$url = 'http://'.$j.'/api.cgi';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($curl, CURLOPT_POSTFIELDS, '{"command":"login","data":{"username":"admin","password":"admin"}}');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$resp = curl_exec($curl);
curl_close($curl);
$jresp=json_decode($resp);
$sessionID=$jresp->data->id->sessionID;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($curl, CURLOPT_POSTFIELDS, '{"command":"setdatapointvalue","data":{"sessionID":"'.$sessionID.'","uid":1,"value":1}}');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$resp = curl_exec($curl);
curl_close($curl);
}
turnoff('10.0.0.60');
?>
Basically it's two API calls, one is to authenticate and obtain a SessionID which is then used in a second API query to set a value against it.
Thanks for any improvements offered.