Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute Python script from Php

I have a PHP webpage on my raspberry pi with 2 buttons (on and off) The on button button redirects to On.php The off button redirects to Off.php In "/usr/lib/cgi-bin" I have a python script that I would like to execute (script.py) I can perfectly execute it from the terminal by typing

cd /usr/lib/cgi-bin
sudo python script.py

It works if I do it from the terminal.

The problem is the PHP file (On.php) in my "/var/www" folder. This is what I wrote:

<?php
exec('cd /usr/lib/cgi-bin');
exec('sudo python script.py');
?>

Why is the script executing from the terminal, but not from my PHP?

like image 522
ChubbyChocolate Avatar asked Aug 04 '15 13:08

ChubbyChocolate


People also ask

Can you run a Python script from PHP?

To run a Python script from PHP, we can use the shell_exec function. $command = escapeshellcmd('/usr/custom/test.py'); $output = shell_exec($command); echo $output; to call escapeshellcmd to escape the command string. Then we call shell_exec to run the $command .

How do I run a Python script from a PHP script?

php $command_exec = escapeshellcmd('path-to-. py-file'); $str_output = shell_exec($command_exec); echo $str_output; ?> The right privileges need to be given so that the python script is successfully executed. Note − While working on a Unix type of platform, PHP code is executed as a web user.

Can we integrate Python with PHP?

You can execute python scripts using the exec() function in your php script.


1 Answers

You can't use sudo from a PHP script. Apache is running from an user (www-data generaly), so edit this file : /etc/sudoers

Then add this line :

www-data ALL=(ALL) NOPASSWD:ALL

Care ! this will authorize all functions to be called by a PHP script, you can adapt changing "ALL" by your script or Python command.

Then precise your user in your exec command :

<?php
exec('sudo -u www-data python /usr/lib/cgi-bin/script.py')
like image 125
Vincent Decaux Avatar answered Sep 18 '22 16:09

Vincent Decaux