0

I'm trying to execute a python script from PHP... But I'm getting a wierd output... In my Python script there is GPIO statements to control the relay and a print statement... Now the wierd thing is the print statement gets executed but not the GPIO statement... No errors are there... I have also provided execute permission for my python file... I don't know what's the problem... Python gets executed not the ""GPIO"" :( :( The Python code(relay.py) I used is:

import sys
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
pin=11
GPIO.setup(pin,GPIO.OUT)
i=sys.argv[1]
n=int(i)
if(n==0):
    print(n)
    GPIO.output(pin,GPIO.LOW)
if(n==1):
    print(n)
    GPIO.output(pin,GPIO.HIGH)

The PHP(lightonoff.php) code is:

<form method="post" action="php.php">
    <input type="submit" value="on">
    <input type="hidden" name="ct1" value="1">
</form>
<form method="post" action="php.php">
    <input type="submit" value="off">
    <input type="hidden" name="ct1" value="0">
</form>

The php.php file is:

<?php
    $i=$_POST['ct1'];
    $r=exec("/var/www/html/relay.py $i");
    echo $r;
?>

1 Answers1

0

consider using passthru instead of exec, so you can read the command's output, using 2>&1 at the end of the command, so STDERR and STDOUT are also visible. that will help. additionally, your command you may need to do CHMOD and CHOWN in order to ensure permissions and mark the executable byte flags. also, you may beed to have a shebang line with the command line interpreter (in this case, python) as well .

also, use escapeshellcmd to sanitize $_POST input so attackers don't execute arbitrary shell commands by changing the variable!!

Should I put #! (shebang) in Python scripts, and what form should it take?

http://php.net/manual/en/function.escapeshellcmd.php

Community
  • 1
  • 1
Felipe Valdes
  • 1,998
  • 15
  • 26