3

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)
3

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");
|improve this answer|||||
1

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.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.