Freek
Freek

Reputation: 1189

Execute code to switch light on with PHP

I would like to execute a program using PHP, a piece of code that will use an RF transmitter to switch in my lamp.

This is achieved from the command line by:

action 63 A on

It is just a C program someone wrote to control the GPIO pins on my raspberry pi. So I make an index.php

<?php
exec('action 63 A off');
?>

It does nothing while:

<?php
echo exec('action');
?>

Gives me the default text output of the program (an explanation on parameters to use). This tells me PHP works, the program is located, it can be executed. But my lamp is not switching on. Moreover, typing on the command line:

php index.php

Does switch my lamp on/off as expected! (Using the first variety of the file) Is Nginx (user http) not allowed to switch the lamp on/off? It is allowed to execute the file, at least, it can make it generate text output.

I also tried:

<?php
system('action 63 A off');
?>

And some more varieties like shell_exec

And thoughts?

Upvotes: 4

Views: 1875

Answers (3)

Freek
Freek

Reputation: 1189

I solved it. The answer was easy, indeed the user "http" was not allowed to execute things from the wiringpi library which the C-program needed to run.

In the end I simply did:

chmod +s action

(This sets modifies the executable (called "action") to always run with root privileges.) ...and the code ran as expected with the following PHP file (index.php):

<?php
system('action 63 A off');
?>

Thanks for all the help!

Upvotes: 2

Uours
Uours

Reputation: 2492

Considering echo exec('action') is working but not exec('action 63 A off') , it is seeming that the command is failing if there parameters .

If that is the case , why not make two shell scripts / batch files one for On and one for Off , and call those from PHP ?

File switch_on contents :

action 63 A on

File switch_off contents :

action 63 A off

Make sure switch_on and switch_off files are accessible by PHP and have Execute permission .

switch_on.php

<?php
    exec('switch_on');
?>

switch_off.php

<?php
    exec('switch_off');
?>

Upvotes: 0

Chris
Chris

Reputation: 95

is the C program a binary that you can pass parameters to? If so the following should work.

string exec ( string $command [, array &$output [, int &$return_var ]] )

for example

exec("controller.exe {$data}",$output);

data being parameters to pass into the executable, and output being any response from the executable.

See here for an example

Upvotes: 0

Related Questions