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.
2
Answers
I’m not a very experienced person. One idea you can do, you write the curl call in a different function and pass the necessary parameters to it.
Then use that function twice in this
turnoff($j)
function. In that way your code will be little optimized. I’m sure you have think about it also.My stack-overflow reputation is not enough otherwise I’ll add comment on top. Thanks in advance if it helps.
json_encode
to construct JSON strings is the ideal way to create a JSON string and not hardcoding the string as JSON via trial and errors.sessionID
.this
.Snippet: