I am running a PHP document on an Apache server on my Raspberry Pi and I want it to run a file when a button is clicked. I put some echo commands under the command to make the file run and it prints out but the file doesn't run. The index.php file and lightson.py and lightsoff.py files are all in the same directory (/var/www) and I have added #!/usr/bin/env python to the top of both files and made them executable by using chmod +x lightson.py. If I run the command from the shell it works and turns on the light just like I want with the exact same command as in the file but yet it wont run through the command. The code:
<html>
<head>
<title>Light Controller</title>
</head>
<?php
if (isset($_POST['LightON']))
{
shell_exec("sudo python /var/www/lightson.py");
echo("on");
}
if (isset($_POST['LightOFF']))
{
shell_exec("sudo python /var/www/lightsoff.py");
echo("Off");
}
?>
<form method="post">
<button name="LightON">Light ON</button>
<button name="LightOFF">Light OFF</button><br><br>
</form>
</html>
as you said you are running it like
apache->php->shell_exec(SUDO..)
So the apache user has to be in sudoers file, better you don't give sudo to apache instead give apache (www-data) user right to run your python program
put first line in your python script:
#!/usr/bin/env python
so the script knows which program to open it with..then
change group:
make it executabel
try it
I hope it works ;)
TIPP: Apache and PHP are for delivering
Documents and Strings
, if you want some kind of control and an API start with nodejs and https://www.npmjs.com/package/rpi-gpio package. This way you will have one place for your solid automation environmentThis worked for me:
test.php
test.py
Here's my relevant
ls -l
output from/var/www/html
:Since I don't have GPIO pins on my laptop, I decided to write to a file as a test. Notice I didn't have to use
sudo
because of the way I set the permissions ontest.py
.