PHP HTTP CURL PUT request for LIFX Power On/Off

2019-03-04 15:54发布

问题:

I'm trying to power all of my Lifx bulbs on/off using PHP.

The API documentation, http://developer.lifx.com/, says to use a PUT request:

curl -u "c87c73a896b554367fac61f71dd3656af8d93a525a4e87df5952c6078a89d192:" \
       -X PUT \
       -d "state=on" \
       "https://api.lifx.com/v1beta1/lights/all/power"

Now using that curl command works in the command line. It prompts me for my password unless I add it after the colon in the "username".

The trouble is when I try to translate that command into PHP like so:

$authToken = 'c87c73a896b554367fac61f71dd3656af8d93a525a4e87df5952c6078a89d192:myFakePassword';
$ch = curl_init('https://api.lifx.com/v1beta1/lights/all/power');
$headers = array("selector=all&state=on",'Authorization: Bearer ' . $authToken);
curl_setopt($ch, CURLOPT_PUT, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);

This goes through, but I get a 404 Not Found which the Lifx documentation says is probably a malformed selector.

Note: I was able to make a successful call with PHP to toggle the power with this POST:

$authToken = 'c87c73a896b554367fac61f71dd3656af8d93a525a4e87df5952c6078a89d192';
$ch = curl_init('https://api.lifx.com/v1beta1/lights/all/toggle');
$headers = array("selector=all",'Authorization: Bearer ' . $authToken);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);

But I don't want to just toggle the lights, I want to be able to specify on or off. What could be wrong with my PUT request?

Thank you for any suggestions.

回答1:

Solved this by setting some other curl options:

$ch = curl_init($link);
$headers = array('Authorization: Bearer ' . $authToken);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$data = "state=on";
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);

$link is https://api.lifx.com/v1beta1/lights/all/power

$authToken is my api key