A PHP library to play with the Raspberry PI's GPIO pins

Overview

php-gpio

php-gpio is a simple PHP library to play with the Raspberry PI's GPIO pins.

It provides simple tools such as reading & writing to pins.

Latest Stable Version Build Status Scrutinizer Code Quality SensioLabsInsight Total Downloads

Circuit snapshot

[UPDATE Fall 2014] Now compatible with both Raspberry Pi B Model & B+ Revision

Tl;dr

- "Hey, I just want to blink a LED from my raspberry pi hosted website!"
- "OK good guy: git clone https://github.com/ronanguilloux/php-gpio-web.git`
   & remember to come back here when you're lost ;-)"

=> php-gpio-web: a simple example for you to play with Leds & PHP

GPIO

General Purpose Input/Output (a.k.a. GPIO) is a generic pin on a chip whose behavior (including whether it is an input or output pin) can be controlled (programmed) through software. The Raspberry Pi allows peripherals and expansion boards (such as the Rpi Gertboard) to access the CPU by exposing the inputs and outputs.

For further informations about the Raspberry Pi's GPIO capabilities, see docs & schemas at http://elinux.org/RPi_Low-level_peripherals.

For Raspbeery Pi's GPIO controlling LEDs, have a look at a sample complete circuit diagram for a single LED, with detailled explanations & schemas, here.

For Raspbeery Pi's GPIO controlling sensors, check the DS18B20 (temperature sensor) in action here

Hardware prerequisites

After having installed & wired your LED & resistor on a breadboard, add appropriate modules from the Linux Kernel:

For LEDs, enable the gpio module :

$ sudo modprobe w1-gpio

(see a complete circuit diagram for a single LED + explanations & schemas here)

For sensors, enable the appropriate sensor. By example for a DS18B20 1-Wire digital temperature sensor:

$ sudo modprobe w1-therm

(see the DS18B20 in action on a Raspberry Pi here)

To load such kernel modules automatically at boot time, edit the /etc/modules file & add these two lines:

w1-gpio
w1-therm

Installation

The recommended way to install php-gpio is through composer.

Just run these three commands to install it

$ sudo apt-get install git
$ wget http://getcomposer.org/composer.phar
$ php composer.phar create-project --stability='dev' ronanguilloux/php-gpio intoYourPath

Now you can add the autoloader, and you will have access to the library:

<?php

require 'vendor/autoload.php';

If you don't use neither Composer nor a ClassLoader in your application, just require the provided autoloader:

<?php

require_once 'src/autoload.php';

API Usage

The API usage requires sudo permissions.
To respect such permissions needs (say, for any web-related usage), see blinker file and the explanations below.

<?php

require 'vendor/autoload.php';

use PhpGpio\Gpio;

echo "Setting up pin 17\n";
$gpio = new GPIO();
$gpio->setup(17, "out");

echo "Turning on pin 17\n";
$gpio->output(17, 1);

echo "Sleeping!\n";
sleep(3);

echo "Turning off pin 17\n";
$gpio->output(17, 0);

echo "Unexporting all pins\n";
$gpio->unexportAll();

Understanding I/O permissions

Permissions make sense:

  • it's bad practice to run your webserver user (say, Apache2's www-data) as root
  • it's bad practice to chmod 777 /dev only because someone wants to blink a led freely

Such practices are regularly proposed on RPi forums, but they aren't security-aware & therefore not recommendable in an Internet environment. Instead, the good old /etc/sudoers file allow your linux users to execute single files with sudo permissions without password to type.

The blinker file solution ("one-file-to-blink-them-all")

In a PHP-based project, the API can only be used with sudo permissions. But there is a solution to avoid exposing your Raspbery Pi to security issues : Preparing & packaging inside an API client, in a single PHP file, the GPIO operation you need to run. In a hardware-based project, such operations are usualy few in number: blink a led, run a servomotor, etc. Such single PHP file containing your GPIO-related action can be called with determinated parameters from within your web-based application using exec() command :

(...)
$result = exec('sudo -t /usr/bin/php ./blinker 17 20000'); // calling the API client file
(...)

Such one-single PHP file to act as an API client for one GPIO action makes easier to configure specific sudo permissions in your /etc/sudoers file, as you'll see below. If you have more hardware operations to run (say, a LED + a servomotor + 2-3 sensors), more dedicated API client files, with their own parameters, is also very OK.

As an example of such solution, we provide a simple blinker php file, executable from the shell & from within your web based app. To run this blinker with sudo permissions but without password inputting, just allow your www-data or your pi user to run the blinker script using exec(). With the solution provided below, only one blinker script is needed to manage all your leds, and your webserver application needs only one php file to be specified in /etc/sudoers.

This is the regular linux-file-permission-system way to do such things, not a dummy chmod 777 bullshit.

Edit your /etc/sudoers file:

$ sudo visudo

Then add this two lines in your /etc/sudoers file :

    www-data ALL=NOPASSWD:/path/to/the/blinker

Replace /path/to/the/blinker with your single API client PHP file.

The blinker file provided now has the sufficient permissions & is ready to use the GPIO API. You do not need to install apache2-suexec nor suPHP.

You can test the blinker file solution with the blinkerTest.php file provided here:

<?php

# blinkTester.php

# Blinks the LED wired to the GPIO #17 pin with 0.2 second delay:
$result = exec('sudo -t /usr/bin/php ./blinker 17 20000');

Test your blinker:

$ php blinkTester.php

API Implementations

Some php-gpio api examples / demo :

  • Temperature-Pi: a simple php project reading & logging temperatures using a DS18B20 1-Wire digital temperature sensor & this php-gpio library.
  • Php-Gpio-Web: a website damn simple integration example of the php-gpio lib

Unit Tests

Running the full PhpUnit tests set over php-gpio requires a sudoable user, because of various gpio operations. Instead of installing phpunit, you can just download & use the single PhpUnit package. This can be easily done using cURL, to get the standalone PhpUnit's phar file:

$ wget http://pear.phpunit.de/get/phpunit.phar
$ chmod +x phpunit.phar
$ wget http://getcomposer.org/composer.phar
$ php composer.phar install --dev
$ sudo /usr/bin/php phpunit.phar

PHP Quality

For PHP quality fans, and for my self coding improvement, I wrote a little script available in the ./bin directory I launch to check my PHP code: It produces various stats & metrics & improvements tips on the code.

Credits

License

php-gpio is released under the MIT License.
See the bundled LICENSE file for details.
You can find a copy of this software here: https://github.com/ronanguilloux/php-gpio

Comments
  • getVersion() not working on B+

    getVersion() not working on B+

    This line is not working with B+ version (revision 0010). https://github.com/ronanguilloux/php-gpio/blob/master/src/PhpGpio/Pi.php#L12

    Looking in revision tables, maybe just with a return hexdec($matches[1]) gone work.

    enhancement 
    opened by paucapo 4
  • Permissions Issue

    Permissions Issue

    I seem to be having a problem controlling the GPIO pins using this script.

    It seems to stem from the fact that the directories in

    /sys/class/gpio

    and their symlinked companion

    /sys/devices/virtual/gpio

    keep reverting back to being root:root.

    Additionally, if I set the ownership to pi:pi and add read/write to group permissions the directory for the pin I'm accessing empties itself.

    I feel like I'm missing something really obvious. At the moment my Apache server is running as pi:pi. What permissions and ownership do I need to set to make this work?

    question 
    opened by Gisleburt 3
  • Permissions for Exec

    Permissions for Exec

    Hi,

    I have been dealing with the Exec command, and the only way that worked for me was exec('sudo php blinker 17 20000');

    It needed the php command, is this a permissions issue? It works fine localy, but through the network it doesn't.

    question 
    opened by mbalderas 2
  • Pin number 16 invalid

    Pin number 16 invalid

    Im trying to convert this python https://gist.github.com/gsdevme/3ac674eb105b13d0139d

    I have repo setup here https://github.com/gsdevme/energenie-pi-remote-control however running it on the Pi I get pin number 16 invalid

    https://github.com/gsdevme/energenie-pi-remote-control/blob/master/test.php

    # set the pins numbering mode
    GPIO.setmode(GPIO.BOARD)
    

    The python has this call unsure if its a problem, any ideas exactly?

    opened by gsdevme 1
  • Added the MCP3002 analog to digital converter as a sensor

    Added the MCP3002 analog to digital converter as a sensor

    Hi, I found very useful your code and I used it to implement a power supply tension reader through the use of a MCP3002 ADC. So I implemented a new sensor to read data from a MCP3002 using php-gpio.

    opened by paolocasarini 1
  • B+ Revision check & Pins

    B+ Revision check & Pins

    This was my attempt at creating a PR for issue #8. I was not sure what to do with the hackablePins array as I'm not entirely sure what the purpose of that array is. Hope this helps get things up to date for the B+. Changes seem to be working okay with mine when it comes to reading pins, have no started messing with blinking pins.

    opened by alexciarlillo 1
  • Clarification on API

    Clarification on API

    The API can only be used with sudo permissions correct? The blinker file is separate and used for secure cases, but there is no safe/secure way to use the API for a web based application?

    Thanks

    question 
    opened by alexciarlillo 1
  • Update credits

    Update credits

    Hey,

    Can we update the URL from https://github.com/pickley/PHP-GPIO to https://github.com/aaronpearce/PHP-GPIO.

    Just changed my Github name so the link will 404 :)

    opened by aaronpearce 1
  • "git was not found" when installing from composer

    (received from David P., I write it back here in case it serves to others users )

    I have tried to install the php gpio library and I seem to be running into a problem. Please forgive me, I am a beginner. I'm sure I'm missing something very fundamental :)

    Following instructions at https://github.com/ronanguilloux/php-gpio

    When I try to execute

    php composer.phar create-project --stability='dev' ronanguilloux/php-gpio intoYourPath

    I get an error

    [RuntimeException] Failed to clone http://github.com/ronanguilloux/php-gpio.git, git was not found, check that it is installed and in your PATH env.

    sh: 1: git: not found I also get errors in my PHP when I try to

    question 
    opened by ronanguilloux 1
  • Scrutinizer Auto-Fixes

    Scrutinizer Auto-Fixes

    @ronanguilloux requested this pull request.

    This patch was automatically generated as part of the following inspection: https://scrutinizer-ci.com/g/ronanguilloux/php-gpio/inspections/1115dd77-1c88-4880-88e4-d8d4c583ce78

    opened by scrutinizer-auto-fixer 0
  • Scrutinizer Auto-Fixes

    Scrutinizer Auto-Fixes

    @ronanguilloux requested this pull request.

    This patch was automatically generated as part of the following inspection: https://scrutinizer-ci.com/g/ronanguilloux/php-gpio/inspections/a97307d9-9d52-486f-9cae-1f31e7e1b833

    Enabled analysis tools:

    • PHP Analyzer
    • PHP PDepend
    • PHP Similarity Analyzer
    • PHP Change Tracking Analyzer
    opened by scrutinizer-auto-fixer 0
  • Permission Denied - file_put_contents(/sys/class/gpio/gpio23/direction): failed to open stream: Permission denied

    Permission Denied - file_put_contents(/sys/class/gpio/gpio23/direction): failed to open stream: Permission denied

    Hi there, i'm using your package with Laravel 5.5 and Nginx+Php-fpm I had a problem:

    file_put_contents(/sys/class/gpio/gpio23/direction): failed to open stream: Permission denied

    Any idea?

    opened by msdme 0
  • Permissions are not set, pelase provide example

    Permissions are not set, pelase provide example

    Hi There.

    I am sorry to bring this up, but could the permissions settings also be addressed here more, because this does not work without them, using Raspberry Pi2 and Jessie 2017 image.

    When user starts this from the pure clean jessie image and installs apache2 with php5 pi user loggind in, , GPIO permissions are not right and this does not work. Sudo php index.php does the trick. I would ask for clean commands on how to make this work. After Apache2 & PHP installations, I use "sudo chown pi.pi /var/www/html -R" so that I can SFTP stuff in.

    Thank you for your considerations.

    opened by Erfeniuses 0
  • Support for Raspberry Pi 3

    Support for Raspberry Pi 3

    For my Raspberry Pi 3 it doesn't detect the right version number in Pi->getVersion(). It returns 0 instead of 4. Therefore I can't use certain pins without it complaining. I would have made a pull request if I could but I don't know how to convert the revision numbers (http://www.raspberrypi-spy.co.uk/2012/09/checking-your-raspberry-pi-board-version/)

    opened by winternet-studio 5
  • Fix of a permission denied error caused by delay of GPIO pin exporting.

    Fix of a permission denied error caused by delay of GPIO pin exporting.

    When I use Gpio class directly from webpage (for example from index.php file through Apache) it return me a Permission dennied error. I have found out that it was caused by delay (around 0.04s) when the setup method exported GPIO pin.

    opened by martinvysnovsky 0
  • run servomotor using this library

    run servomotor using this library

    Hi I am trying to simulate PWM by writing this code to run a servomotor

    #!/usr/bin/env php
    <?php
    
    require 'vendor/autoload.php';
    
    use PhpGpio\Gpio;
    $gpio = new GPIO();
    $gpio->output(18,0);
    while(true)
    {
    $gpio->output(18,1);
    usleep(1500);
    $gpio->output(18,0);
    usleep(2000000);
    }
    

    but the servo is not working, a similar code is written in python on this video and it is working: http://www.youtube.com/watch?v=ddlDgUymbxc&feature=youtu.be

    any ideas?

    opened by H889761123 1
Releases(v1.0.0)
  • v1.0.0(Jul 7, 2013)

Owner
Ronan Guilloux
Having fun with Open-Source since 1998.
Ronan Guilloux
Class for manage directly leds on raspberry pi in PHP

led_raspberry Class for manage directly leds on raspberry pi in PHP We can access GPIO ports directly with fwrite() for power on|off leds, without use

Rafael Martin Soto 8 Sep 15, 2021
Raspberry Pi Self Hosted Server Based on Docker / Portainer.io

Pi-Hosted Portainer Template V2 This repository is a collection of tutorials for hosting a variety of server applications using Docker and Portainer.

don 776 Jan 8, 2023
A now playing screen for the Raspberry Pi using the Last.fm API.

raspberry-pi-now-playing A now playing screen for the Raspberry Pi using the Last.fm API. This project is detailed, with photos of how I used it with

null 44 Dec 17, 2022
Raspberry Pi wifi hotspot with an offline-first community portal. Optionally shares internet access over Tor.

Raspberry Pi wifi hotspot with an offline-first community portal. Optionally shares internet access over Tor.

Martti Malmi 17 Dec 15, 2022
PHP exercises from my course at ETEC and some of my own play-around with PHP

etec-php-exercises PHP exercises from my course at ETEC and some of my own play-around with PHP Translations: Português (BR) Projects Project Descript

Luis Felipe Santos do Nascimento 6 May 3, 2022
PHP scraper to get data from Google Play

nelexa/google-play-scraper PHP library to scrape application data from the Google Play store. Checking the exists of the app on Google Play. Retrievin

Pisarev Alexey 57 Dec 20, 2022
Get mobile app version and other related data from Google Play Store, Apple App Store and Huawei AppGallery

Mobile App Version Get mobile app version and other related data from Google Play Store, Apple App Store and Huawei AppGallery. Installation Add to co

Omer Salaj 11 Mar 15, 2022
It's goal is to create my own platform where I can play various board games I like.

Card games The goal of this project is to create a social platform where players can communicate, create lobbies and play various board games. Current

Ondřej Mastík 2 Oct 29, 2021
This plugin allow you play music from resources pack in minecraft

Music Player for PocketMine-MP Commands music-start songname music-stop songname IMPORTANT! You must add music resources pack to PocketMine resources

Excalibur 1 Oct 14, 2021
Plug-and-Play Custom Enchants Plugin For PocketMine-PMP

DEVELOPER'S NOTE: I can tell you right now this plugin hasn't been tested. I haven't even checked to see if it loads without crashing yet. Half of thi

VANIC 10 Oct 23, 2021
Plug-and-Play Custom Enchants Plugin For PocketMine-PMP

DEVELOPER'S NOTE: I can tell you right now this plugin hasn't been tested. I haven't even checked to see if it loads without crashing yet. Half of thi

VANIC 10 Oct 23, 2021
A good plugin to play a sound when the player hits the enemy's head

HeadshotSound A good plugin to play a sound when the player hits the enemy's head. How to use Hit the player with a snowball, egg and bow in the head

Laith Youtuber 6 Nov 3, 2022
Scorm Player Api for play scorm modules

flux-scorm-player-api Scorm Player Api for play scorm modules Installation Native Download RUN (mkdir -p /%path%/libs/flux-scorm-player-api && cd /%pa

null 1 Dec 12, 2022
Dobren Dragojević 6 Jun 11, 2023
Easy to use utility functions for everyday PHP projects. This is a port of the Lodash JS library to PHP

Lodash-PHP Lodash-PHP is a port of the Lodash JS library to PHP. It is a set of easy to use utility functions for everyday PHP projects. Lodash-PHP tr

Lodash PHP 474 Dec 31, 2022
PHP Text Analysis is a library for performing Information Retrieval (IR) and Natural Language Processing (NLP) tasks using the PHP language

php-text-analysis PHP Text Analysis is a library for performing Information Retrieval (IR) and Natural Language Processing (NLP) tasks using the PHP l

null 464 Dec 28, 2022
php-echarts is a php library for the echarts 5.0.

php-echarts 一款支持Apache EChart5.0+图表的php开发库 优先ThinkPHP5/6的开发及测试。 Apache EChart5.0已经最新发布,在视觉效果、动画效果和大数据展示方面已经远超之前的版本; 故不考虑EChart5.0之前版本的兼容问题;建议直接尝试5.0+

youyiio 5 Aug 15, 2022
Minimalist PHP frame for Core-Library, for Developing PHP application that gives you the full control of your application.

LazyPHP lightweight Pre-Made Frame for Core-library Install Run the below command in your terminal $ composer create-project ryzen/lazyphp my-first-pr

Ry-Zen 7 Aug 21, 2022
Gettext is a PHP (^7.2) library to import/export/edit gettext from PO, MO, PHP, JS files, etc.

Gettext Note: this is the documentation of the new 5.x version. Go to 4.x branch if you're looking for the old 4.x version Created by Oscar Otero http

Gettext 651 Dec 29, 2022