Search code examples
phppythonapacheraspberry-piraspbian

Cannot execute a python script from php inside an if-else statement


I am on raspberry pi and i am using an apache server. The PHP code will execute the python script if id in the url is even. The python script runs perfectly fine when it is outside the if-else block.

<?php
$op=shell_exec("python /home/pi/hi.py");
echo $op;

$id = intval($_GET["id"]);
echo $id."\n";
?>

But when placed in the if-else block it fails to work.

<?php    
$id = intval($_GET["id"]);
echo $id."\n";

if($id%2==0)
echo "Even";
$op=shell_exec("python /home/pi/hi.py");
echo $op;
else
echo "Odd";   
?>

I am new to php and I cannot seem to understand the problem.


Solution

  • else is actually a syntax error in this case. Without braces around the statements after if, PHP expects one statement to follow it. Since there are more than one, the else is unexpected when it is reached.

    Adding the braces should fix the problem.

    if ($id%2==0) {
        echo "Even";
        $op=shell_exec("python /home/pi/hi.py");
        echo $op;
    } else {
        echo "Odd";
    }
    

    Generally, I think it's a good idea to just always use the braces, even if you do have only one statement. That way when you add more statements later, you won't run into this problem.