It works! Okay, back up a little. Getting a PHP web interface to talk to hardware proved to be rather difficult. You need root access to control hardware but the web service runs with minimal permissions. So how does one bridge the gap without compromising the system? The answer, very carefully. I found a few workarounds but they involved either using MySQL or the gpio-admin library that works from commandline or shell scripts. In my case I wanted to stay with using C programs with the wiringPi library being called from PHP. C is much faster to control GPIO and PHP gives me a web front end. Here is how I did it.
First the PHP process needs a way to run the binary as root. In this example, I am using the blink.c program. The way we do this at the command line is “sudo” but this required a password and PHP wouldn’t be able to do that without exposing your password. What we do know is apache/lighttpd is running at the user “www-data”. Hmm, what can we do there?
- Create a blink.c and compile it. If you need help look at this post Raspberry Pi CommandIR and Beyond
- Edit the sudoers file.
- sudo visudo
- Under “User privilege specification” add this
- www-data ALL=NOPASSWD: /path/to/binary, /path/to/another/binary
- Save and exit (had a hard time with this for some reason, I used ESC CTRL-C Y ENTER CRTL-C CTRL-C(Looks like Wheezy works the normal way for nano)
- Then in your PHP script you can call it like this
- $result=exec(‘sudo /path/to/binary’);
print ('Blinking LED...');
$result=exec('sudo gpio/blink'); //or ('sudo gpio/blink > /dev/null &')
<FORM NAME="blink" Method='POST'>
<button name="blink">Blink LED</button>
Just copy and paste this code into a PHP file (blink.php) and save it to the root of your web folder. It should should be /var/www/.
Here are the links to the other options if they work for you:
In case you are using python which uses GPIO-Admin
Edit: If you want it to blink the LED in the background and return control to the webpage right away change
$result=exec(‘sudo gpio/blink > /dev/null &’);
Many thanks from Portugal.
This was very helpful, cheers from Sweden! 😀
Thanks from Denmark!
thank you so much, yo're the only one on the entire internet who solved my problem.
Thanks From Indonesia
Thanks from France!! the only solution works on the Internet!
It works very well but not with html.
ex : print("Hello
") doesnt' work
Try using echo instead.
Thank you from Greece! Keep up the good work!
Veery thanks from Poland. <3