Raspberry Pi – Using it as Web Server and for PHP • Russwurm

Raspberry Pi – Using it as Web Server and for PHP

There is a whole lot of cool stuff which can be done with the Raspberry Pi and it would be amazing to control this stuff by your browser / mobile phone / … The easiest way to do this is setting up a web server on the RaspPi and use PHP to execute interesting things.

Installing the Web Server

Here the simple steps to get an Apache web server running.

# Just update to make sure we have all the stuff we need
sudo apt-get update
# Now install Apache
sudo apt-get install apache2
# Starting Apache manually - just for reference
sudo service apache2 start
# Autostart of Apache - should be already the default
sudo insserv apache2

Installing PHP on Raspberry Pi

Next the installation of PHP on the Raspberry Pi.

# most important modules
sudo apt-get install php5 php5-common libapache2-mod-php5
# restart Apache
sudo service apache2 restart

The easiest way for testing is creating the file phpinfo.php in the directory /var/www/ and opening it up in the web browser.

The phpinfo.php file:

<?php phpinfo(); ?>

Using PHP to control the GPIO of Raspberry Pi

A small and simple example to control one of the pins which can be turned off and on to see the concept. Just create the following file called control.php in the folder /var/www/ and open it up in the web browser.

   ini_set('display_errors', '1');
   error_reporting(E_ALL ^ E_NOTICE);
   if ($_REQUEST['light'] == 'on') {
      exec('gpio -1 mode 26 out');
      exec('gpio -1 write 26 1');
   } else {
      exec('gpio -1 mode 26 out');
      exec('gpio -1 write 26 0');
   $state = exec('gpio -1 read 26');
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
   if ($state == '0') {
      echo '<h2><a href="./control.php?light=on">Light On</a></h2>';
   } else {
      echo '<h2><a href="./control.php?light=off">Light Off</a></h2>';