Send Real Time Notification to Clients Through Pusher in PHP


Sometimes we need to send real-time notifications to our clients. But implementing it through ajax is extremely not recommended as frequent Ajax request can slow down your server and in the rear case can cause Slowloris attack in your apache server since apache server makes threads for each request. So the best and the correct way to implement the real-time system is through web socket connections thus the connection is always established between clients and server without the need to overload server through continuous requests. In this tutorial, I will show how to send the free real-time notifications to real time clients through Pusher in PHP.

Before we start coding we need to make an application in Pusher and need to get application key and secret. The application creation is very easy and straight forward process. All you need to do is just sign up with your Google or GitHub account to Pusher by visiting  pusher.com. Their basic plans are completely free.

Now to make standard bootstrap alerts into "growl" like notifications I am using a free plugin called Bootstrap Notify. You can also download it from http://bootstrap-notify.remabledesigns.com/

Let's Start Coding

We need to create two pages one for the clients to show notifications and one for the server to send notifications to clients. In client page, we use some javascript codes to establish a connection to Pusher through a socket based connection. The javascript codes in the client's pages which we need to show real-time notification are given below.

<script src="https://js.pusher.com/4.0/pusher.min.js"></script>
<script>

	// Enable pusher logging - don't include this in production
	Pusher.logToConsole = true;

	var pusher = new Pusher('your app key', {
	  cluster: 'ap2',
	  encrypted: true
	});

	var channel = pusher.subscribe('my-channel');
	channel.bind('my-event', function(data) {
		console.log(data.message);
		
	});

</script>

 

Now in server side, we will send our notifications to all connected clients through pusher. The server side code for sending the notification to clients is given below.

require('vendor/autoload.php');

$options = array(
'cluster' => 'ap2',
'encrypted' => true
);
$pusher = new Pusher(
'your app key', // app key
'your app secret', // app secret
'your app id', // app id
$options
);

$data['message'] = 'Hello Friends';
$pusher->trigger('my-channel', 'my-event', $data);

 

Note

You need to download Pusher library for PHP by using composer before doing server side coding. If you are not familiar with the composer, It is just a Dependency Manager for PHP. You can easily download it from https://getcomposer.org/. After installing it navigate to your project folder through terminal or cmd and paste the command given below. A vendor folder is created inside your project folder which contains all your libraries. Now require the autoload.php file inside vendor folder in all your server side pages. 

composer require pusher/pusher-php-server

Now Let's Create A Demo App

In this demo application we will accept a name from the client-side text box and send it to the server through jquery ajax post function and then the client will send a push notification to all connected clients through pusher. 

Index.html

The complete code for an index.html page of our demo application is given below.

<!DOCTYPE html>
<head>
	<title>Pusher Notification Demo</title>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	
	<!-- Bootstrap 3 -->
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

	<!-- Bootstrap Notify - Optional -->
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-notify/0.2.0/css/bootstrap-notify.min.css" >
	<script src="https://shareurcodes.com/js/bootstrap-notify.min.js" ></script>
  
	<!-- Material Design Lite Custom - Optional -->
	<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
	<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-deep_purple.min.css" />
  
	<!-- Pusher -->
	<script src="https://js.pusher.com/4.0/pusher.min.js"></script>
	<script>

	// Enable pusher logging - don't include this in production
	Pusher.logToConsole = true;

	var pusher = new Pusher('your app key', {
	  cluster: 'ap2',
	  encrypted: true
	});

	var channel = pusher.subscribe('my-channel');
	channel.bind('my-event', function(data) {
		console.log(data.message);
		$.notify(data.message, {
			newest_on_top: true
		});
	});


	</script>
	
	<style type="text/css">
		.pagination>.active>a, .pagination>.active>a:focus, .pagination>.active>a:hover, .pagination>.active>span, .pagination>.active>span:focus, .pagination>.active>span:hover {
			background-color: rgb(124,77,255);
		}
		[data-notify="container"] {
			background-color: rgb(241, 242, 240);
			border-color: rgba(149, 149, 149, 0.3);
			border-radius: 5px;
			right : 100px !important;
			color: rgb(124,77,255);
			font-size : 18px;
			font-weight : bolder;
		}
	</style>
</head>
<body>
	<div class="container">
		<p>&nbsp;</p>
		<p>&nbsp;</p>
		<a><h3 class="text-center">Real Time Notification to Clients Through Pusher - Demo</h3></a>
			
			<div class="row">
		        <div class="col-md-10 col-md-offset-1">
					<div class="well">
						<div class="panel panel-default">
							<div class="panel-body">
								<div class="row">
									<div class="col-md-10 col-md-offset-2">
										<form class="form-inline" id="form"  method="post" >
										<div class="form-group">
										  <label for="fromdate">&emsp;Enter Your Name : &emsp;</label>
										  <input type="text"  class="form-control"  name="name" placeholder="Enter Your Name" required>
										</div>
										<div class="form-group">
											&emsp;&emsp;&emsp;<button style="background-color: rgb(124,77,255);color: #fff" type="submit" id="search"  class="btn btn-default">SUBMIT</button>
										</div>
									   </form> 
									</div>
								</div>
							</div>
						</div>
		            </div>
		        </div>
		    </div>
	</div>
	<script >
	$(document).ready(function(){
		  $("#form").on("submit", function(event){
			event.preventDefault(); 
			$.post('server.php',$("#form").serialize());
		});
	});
	</script>
</body>
</html>

Note: I used some custom CSS just for styling the application. It is completely optional in your case. Now I used bootstrap notify plugin to display the notifications. You can use an alert box or anything you like. The jquery ajax post function is used to pass the name to the server side.

server.php

The complete code for server.php file is given below.

<?php
If( $_SERVER['REQUEST_METHOD']  != 'POST'  ){
	die();
}
require('vendor/autoload.php');

$options = array(
'cluster' => 'ap2',
'encrypted' => true
);
$pusher = new Pusher(
'app key',
'app secret',
'app id',
$options
);

if(isset($_POST['name']))
{
	$name = $_POST['name']
}
else
{
	$name = "Client";
}

$data['message'] = 'Hello '.$name;
$pusher->trigger('my-channel', 'my-event', $data);

The server side sends push notification to all clients which are connected to pusher through web socket. 

Now let's see the output image of demo app

Real Time Notification to Clients Through Pusher - Demo - Shareurcodes

 

 The Demo

You can demo above program by visiting following link.

https://shareurcodes.com/demo/pusher/

Note: Open this URL in multiple browsers to make sure that your name is broadcasted to multiple clients real time. If you see any other names when you open this page that is because some other users are testing this demo application.  I am also not saving any of your names in server side so you can test it safely.

If anybody has any suggestions or doubts or need any help comment below and I try will respond to every one of you as early as possible. More tutorials like making real time WebSockets chat application and Facebook chat bot is coming soon. So please stay tuned and leave your suggestions below.


Web development
18th Jun 2017 05:09:04 PM
PHP Javascript jQuery Bootstrap
36157

ShareurCodes

ShareurCodes is a code sharing site for programmers to learn, share their knowledge with younger generation.