Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / IoT / Raspberry-Pi

Connect, Send and Receive data from web page to control PC/RaspberryPi

3.55/5 (6 votes)
9 Jan 2019CPOL2 min read 14.3K   230  
Control Anything from a web page using sockets and ports.

Image 1

Introduction

How to connect to RaspberryPi or any computer using WebPage and Socket so you can access it from any device. (Web server side) In this Article, you will learn how to connect php webpage to RaspberryPi or computer in the same network.

Background

Lately, I developed a robotics solution with remote control Web Application using simple and clean code of PHP, JavaScript, Socket, RaspberryPi, Arduino, LEDs, and Sensors I think it is a good opportunity to share it with the world by explaining them one by one so people can learn from it.

Using the code

This snippet of code is a full control scenario to control a microcontroller board RaspberryPi. The code will include: Firstly: Interface layer or front end with is a web HTML page. Which handle the events to backend, Secondly and the backend is PHP-based code. And finally, RaspberryPi code which will receive the commands and data from php server remotely.

Front End , Back End

Let's start by the first part : Front end contains WebPage as presentation layer.

1- Front End

For simplicity, we will draw a simple HTML page for device image and two Buttons for led on and off.

HTML code

HTML
<html>
	<body>
	..
	..
	<a href="run.php?op=on"> ON </a>// Turn On the Light
	...
	<a href="run.php?op=off"> Off </a> //Turn Off the Light 
	..

Trick: You can wrap it in Ajax as well to avoid refresh :)

Please refer to my trick: Simple Dynamic JavaScript Ajax Function

2- Back End

This is a php code which will connect to the RaspberryPi and send code to it. it will use Sockets.

BackEnd Items :

A- Connection

B- backend PHP page

Connection Socket class

Here is Socket PHP class for connect to RaspberryPi , it contains Read and Write data : read_data, socket_write Also contains open and close socket: open_socket , close_socket

/////////php Code///////
    class Socket{
    public $socket;
    public $host ;
    public $port;

       public function __construct($host,$port){
           $this->host = $host;
           $this->port = $port;

       }
       public function init()
       {
           $this->socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
       }
    public function open_socket()
    {
    $result = socket_connect($this->socket,$this->host,$this->port);
        return $result;
    }
    public function getStatus()
    {
        try
        {
            $status = socket_get_status($this->socket);
            if ($status['timed_out']) {
              return FALSE;
            }
            if ($status=="")
            {
                return TRUE;
            }
        }
        catch (Exception $e) {
            echo $e->getMessage();
        }
    }


       public function send_data($content){

           socket_write($this->socket,$content,strlen($content));

       }

       public function read_data(){
             while($buf = socket_read($this->socket, 1024))
            if($buf = trim($buf))
                break;
        return $buf;
       }

       public function close_socket(){
              socket_close($this->socket);
       }

    }
Prepare command string

To prepare the content of sending data we should commit a data string which we can recognize in RaspberryPi side, for example :

$on = "on";
$off = "off";
$data = "";
$operation = $_GET["op"];
if ($operation =="on")
{

$command = $on;
}
if ($operation =="off")
{

$command = $off;
}

C- Send the command

$connection->send_data($command);

B- backend PHP page

Full Backend Script file

run.php

#include("socket.php");
$RaspberryPiIP = '192.168.1.XXX'; // Change by your RaspberryPi/PC IP 
$RaspberryPiPORT = 5000; // Change by your RaspberryPi / PC Port Number ..
$connection = new Socket(RaspberryPiIP,$RaspberryPiPORT); // Create a new socet Connection object. 
$connection->init();

////////  Get Command from front end page

$on = "on";
$off = "off";
$data = "";
$operation = $_GET["op"];
if ($operation =="on")
{

$command = $on;
}
if ($operation =="off")
{

$command = $off;
}

//// end Get Command from front end page

$connection->open_socket(); // Connect PHP to RaspberryPi or computer.
$connection->send_data($command); //Send command String
$connection->close_socket(); //////////Close connection 
///////////// DONE :)  ///////////////

History

Next I will post Another article for how to receive Socket commands and Excecute it in RaspberryPi. Also I will upload the sourcecode for Full project in GitHub if you liked it. https://gitHub.com/ArabicRobotics

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)