0

For some reason I can't use variables in shell_exec. I already tried changing ' to " but that wouldn't work either.

This works:

<?php
shell_exec('curl --request PUT --data "{\"on\":true, \"bri\":200}" http://192.168.178.21/api/cWRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/lights/2/state');
?>

But This doesn't:

<?php
$status = true;
shell_exec('curl --request PUT --data "{\"on\":$status, \"bri\":200}" http://192.168.178.21/api/cWRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/lights/2/state');
?>
Masivuye Cokile
  • 4,754
  • 3
  • 19
  • 34

1 Answers1

1

You want to concat the strings. Since php displays true to 1, you might want an intermediate variable to set the value of true to "true"

<?php
$status = true;
$string_status = $status ? 'true' : 'false';
shell_exec('curl --request PUT --data "{\"on\":' . $string_status . ', \"bri\":200}" http://192.168.178.21/api/cWRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/lights/2/state');
?>

You can't directly pass variables in a single-quote delimited string. You have to close that string, concat, then re-open.

in example :

<?php
$myVar = "world";
echo "Hello $myVar"; //displays : Hello world
echo 'Hello $myVar'; //displays : Hello $myVar

If you want to use double quote delimited string in your shell_exec(), you'll have to escape the double quotes already in it, such as :

<?php
$status = true;
$string_status = $status ? 'true' : 'false';
shell_exec("curl --request PUT --data \"{\\\"on\\\":$string_status, \\\"bri\\\":200}\" http://192.168.178.21/api/cWRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/lights/2/state");
?>

But that will quickly become unreadable (you'll have to escape the single quotes, and the \" will become \\\"

Cid
  • 14,968
  • 4
  • 30
  • 45