Ok im pretty new to Raspberry Pi and Python/PHP/Apache here. Im trying to get my PHP script to run a python file i created to activate a 5v relay over my home network. In terminal via SSH i can activate the Python script and it controls my relay as it should. When i try and activate the relay via my PHP script on my web server i get nothing. My PHP script and Python script are below. Any help is greatly appreciated!
My Python code is located in /home/pi as "garagedoorleft.py" and my PHP code is located in /var/www/html as "index.php"
<html>
<head>
<meta charset="UTF-8" />
<title>Example document</title>
</head>
<?php
if (isset($_POST['LeftOPEN']))
{
exec("sudo python /home/pi/garagedoorleft.py");
}
?>
<form method="post">
<button name="LeftOPEN">Left Door</button>
</form>
</html>
#!/usr/bin/python
# Import required Python libraries
import RPi.GPIO as GPIO
import time
# Use BCM GPIO references instead of physical pin numbers
GPIO.setmode(GPIO.BCM)
# init list with pin numbers
pinList = [2]
# loop through pins and set mode and state to 'low'
for i in pinList:
GPIO.setup(i, GPIO.OUT)
GPIO.output(i, GPIO.HIGH)
def trigger() :
for i in pinList:
GPIO.output(i, GPIO.LOW)
time.sleep(0.5)
GPIO.output(i, GPIO.HIGH)
GPIO.cleanup()
try:
trigger()
except KeyboardInterrupt:
print " Quit"
# Reset GPIO settings
GPIO.cleanup()
Im not sure how exec
works with pipes and what not but I think you could do
exec("echo SUDO_PASSWORD_FOR_MACHINE | sudo -S -p '' python my_gpio.py")
this passes the sudo password via stdin to the sudo command ... Im not sure how safe it is to do something like this ...
or you could try to elevate privledges yourself
add to the top if the python script
import sys,os
if os.getuid() != 0: # not sudo so spawn as sudo
exit(os.system("echo SUDO_PASSWORD_FOR_MACHINE | sudo -S -p '' python %s"%sys.argv))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.