PHP Sample Code

I was answering a question for someone who was using our HTTP API with PHP the other day and ended up writing some sample code. I thought it might be useful to people here.

If you place your authentication token in $authToken and then run the script it will attempt to turn on all the lights on your LIFX account. If it doesn’t work it outputs the error message from curl, and if it does work it returns the data structure from our API.

<?php

$link = "https://api.lifx.com/v1beta1/lights/all/power";
$authToken = "";
$ch = curl_init($link);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$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);

?>
<html>
  <head>
    <title>LIFX API Test</title>
  </head>
  <body>
    <h1>LIFX API Test</h1>
    <pre><?php
    
    if(curl_errno($ch))
    {
        echo 'Curl error: ' . curl_error($ch);
    } else {
        echo var_dump(json_decode($response, true));
    }
    
    ?></pre>
  </body>
</html>
<?php
curl_close($ch);
?>

@daniel_hall I threw together a whole PHP package you can use composer to install - https://github.com/kz/lifx-php
Still WIP due to lack of tests and exception handling. I’ll find some time to finish it, although if anyone wants to submit a PR in the meantime, go ahead!

Well that is way better than my feeble attempt at an example. If we end up building a page for users to discover LIFX compatible libraries would you be happy if we included this one?

1 Like

Sure, no problem! Feel free to do that.

@ThePurpleK I’ve just submitted a PR to add Laravel support - but not tests or exception handling, my bad! I’m not particularly experienced in writing tests, but if you give me some guidance, I’m sure I can get some coded up!

1 Like

Thanks for the pull request! I’ll add in exception handling and tests soon. Laravel support is always a good idea. :smile:

2 Likes

Hey this is all nifty.

I made a little php CLI controller just for my own enjoyment and to learn the API.

probably a bit tacky but ukno. I just like a CLI thing with colours and hyperlinks in terminal I had fun.

1 Like

I wrote a very easy to use wrapper in PHP. Check it out at: