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?
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')
Try this out, it should be working:
<?php
system("cd /usr/lib/cgi-bin");
system("sudo python script.py");
?>
Or even this:
<?php
system("cd /usr/lib/cgi-bin && sudo python script.py");
?>
On an older Raspbian distribution you need to place your file in /var/www/file.py
. So in your file.php you add:
{
exec("sudo python /var/www/file.py");
}
On a newer Raspbian Jessie you need to place your file in /var/www/html/file.py
, so in your file.php you need to add:
{
exec("sudo python /var/www/html/file.py");
}
Or just any file.py
<?php
{
exec("sudo python test.py");
}
?>
Note: For this to work you need to edit a file first to add these lines to allow passwordless sudo
sudo nano /etc/sudoers
then go to the bottom and add this
pi ALL=(ALL) NOPASSWD: ALL<br>
www-data ALL=(ALL) NOPASSWD: ALL