5

I've been trying to use a site on my local network to activate the GPIO pins on my Raspberry Pi 4. I installed apache and wrote a quick PHP script which executes a python file in /var/www/html.I have a script called LED-on.py, that, when I run directly through the terminal, works with no errors and turns on the LED which I connected through that pin, but if I run it through a PHP shell_exec function and echo the result, I get the error Not running on a RPi!.

echo shell_exec('python /var/www/LED-on.py');
try:
 import RPi.GPIO as GPIO
 GPIO.setwarnings(False)
 GPIO.setmode(GPIO.BCM)
 GPIO.setup(4, GPIO.OUT)
 GPIO.output(4, True)
except Exception as e: print(e)
asked Feb 14, 2020 at 16:29

2 Answers 2

4

It's possible that this might mirror something I was doing a couple of years ago and I preface this with the observation that I don't believe that it was good practice, but I didn't find a way around it, so I welcome any correction.

The issue (in my case) was that running a python program that accessed the GPIO pins required root access. If you are going to execute a python file from PHP, then the user that calles the PHP file will require root (sudo permission) access.

For my part that involved (and here I am paraphrasing to reflect your example) creating a php file that executes the python script similar to;

<?php
echo exec( 'sudo python /var/www/LED-on.py' );
?>

Change the permissions for the python file so that the web user 'www-data' has permissions for the files

sudo chown www-data:pi /var/www/LED-on.py

give the www-data user the ability to run python scripts as root (this is the ugly part)

sudo visudo

Then add www-data ALL=(ALL) NOPASSWD: /usr/bin/python under the # User privilege specification area

It's not secure, but it worked. I would appreciate any advice that would make it better for myself or the OP.

To try and make myself feel better about it I added password protection using 'Web Page Password Protect' by downloading the script from 'http://www.zubrag.com/scripts/password-protect.php', putting it in the same directory as the php file and adding the following line to the top of the .php file;

include("password_protect.php");
answered Feb 15, 2020 at 2:14
3

A little poking with Google suggests this is a permissions problem. I don't have an instance of Apache running on a Pi, but it runs as user www-data on Debian. If that's the case, try sudo adduser www-data gpio, reboot or restart Apache, and test.

answered Feb 14, 2020 at 21:25
1

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.