PHP HTTP CURL PUT request for LIFX Power On/Off

旧时模样 提交于 2019-12-04 06:40:06

问题


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



来源:https://stackoverflow.com/questions/30284346/php-http-curl-put-request-for-lifx-power-on-off

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!