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:
chgrp www-data /path/to/python-script.py
make it executabel
chmod +x /path/to/python-script.py
try it
shell_exec("/path/to/python-script.py");
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 environment
This worked for me:
test.php
<?php
echo shell_exec("python test.py");
?>
test.py
f = open("test.txt", "a+")
f.write("hiya buddy!!\n")
f.close()
print "some output"
Here's my relevant ls -l
output from /var/www/html
:
jason@Jason-one /var/www/html $ ls -l
-rw-r--r-- 1 jason jason 44 Sep 20 18:12 test.php
-rwxr-xr-x 1 jason jason 82 Sep 20 17:44 test.py
-rw-rw-rw- 1 jason jason 38 Sep 20 18:15 test.txt
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 on test.py
.