How to run Python script in PHP under Raspberry Pi?

Hey dreamers! Let’s discuss How to run Python script inside PHP under Raspberry Pi? This instruction assumes that the FTP is enabled and the /var/www folder is already writable. You can check here for more details regarding FTP setup.

Python in PHP

* How to run Python script in PHP under Raspberry Pi?

1. Create a “raspi-ctrl.php” PHP file in var/www/html, then add the sample code below:

<?php
//The $_REQUEST["n"] and $_REQUEST["c"] will serve as python arguments
$str = "sudo python /var/www/html/gctrl.py " . $_REQUEST["n"] . " " . $_REQUEST["c"];
exec($str);

The $_REQUEST[“num”] and $_REQUEST[“cmd”] will serve as python arguments and will have a value of either 1 or 0.

2. Next, create a python file named “gctrl.py” in /var/www/html/, then add the code below:

import RPi.GPIO as GPIO
import sys
 
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
 
#Set specified GPIO pins to OUT
gRelayNumList = [4, 17]
for pinNum in gRelayNumList:
    GPIO.setup(pinNum, GPIO.OUT)
  
#Argument values, num will be GPIO list key and cmd will be for GPIO state
args = sys.argv
num = int(args[1])
cmd = int(args[2])
 
#Turn ON the relay by setting to output to 0 (relay used during test is active low, 0/False will turn ON a switch)
if(cmd == 1):
    #Turn ON
    GPIO.output(gRelayNumList[num], 0)
elif(cmd == 0):
    #Turn OFF
    GPIO.output(gRelayNumList[num], 1)

3. Open the sudoers file using the following command:

sudo nano etc/sudoers.d/010_pi-nopasswd

Warning!!!

a. Do not close nano with 010_pi-nopasswd after editing
b. Open another shell and try sudo command after each editing made on 010_pi-nopasswd. This is to make sure that there are no sudo errors
c. Just to repeat, do not close nano yet and always check for sudo errors, as mentioned in b

4. Add the following codes to 010_pi-nopasswd and save it:

pi ALL=(ALL) NOPASSWD: ALL
yourLoginUsername ALL=(ALL) NOPASSWD: ALL
www-data ALL=(ALL) NOPASSWD: /usr/bin/python /var/www/html/gctrl*

Replace yourLoginUsername with the username you use on your Raspberry Pi.

Important!!!

a. Take note of the points specified in step 3, if 010_pi-nopasswd gets corrupted, sudo will not be available!

5. Open your browser, click the address bar and type the following to call the PHP file:

http://192.168.0.116/raspi-ctrl.php?n=0&c=0

Note: Replace 192.168.0.116 with the IP address of your Raspberry Pi

Leave a Reply

Your email address will not be published. Required fields are marked *

*