Push Notification System with PHP & MySQL

Web Push Notification is a feature to send customized clickable message to display in subscribed user's web browsers like Chrome, Firefox, Safari etc. The push notifications are useful to update user's with specific news, chat, new email and time bound information like offers etc. So if you're thinking about implementing web notification system with PHP, you're here at right place. In this tutorial you will learn how to implement web push notification system with PHP and MySQL. We will cover this tutorial with live demo to save notification message with settings to display to particular users when users logged in.



Here in this example, administrator will create web push notifications with many options and broadcast to logged in users in their browser with many options like:


  • The notification may displayed many times according to settings.

  • The user can also define interval time for the next notification to be displayed.

  • The system will check for the notification every time according to given time

  • The notification will be closed after given time time.



As we will cover this tutorial with live example to implement web push notification system with PHP and MySQL, so the major files for this example is following.



  • index.php

  • login.php

  • manage_notification.php

  • notification.js

  • notification.php

  • Push.php

  • logout.php



Step1: Create Database Tables
First we will create MySQL database table notif_user to store users for login to show notification message to logged in users.

CREATE TABLE `notif_user` (
`id` int(11) NOT NULL,
`username` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


We will also create a table notif to store notification details.

CREATE TABLE `notif` (
`id` int(11) NOT NULL,
`title` varchar(250) NOT NULL,
`notif_msg` text NOT NULL,
`notif_time` datetime DEFAULT NULL,
`notif_repeat` int(11) DEFAULT '1',
`notif_loop` int(11) NOT NULL DEFAULT '1',
`publish_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`username` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;



Step2: Create User Login
Now we will create user login page to allow user login to show notifications to logged in users.

<div class="container">
<h2>User Login:</h2>
<div class="row">
<div class="col-sm-4">
<form method="post">
<div class="form-group">
<?php if ($loginError ) { ?>
<div class="alert alert-warning"><?php echo $loginError; ?></div>
<?php } ?>
</div>
<div class="form-group">
<label for="username">Username:</label>
<input type="username" class="form-control" name="username" required>
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" name="pwd" required>
</div>
<button type="submit" name="login" class="btn btn-default">Login</button>
</form>
</div>
</div>
</div>


we will implement user login functionality on form lsubmit.

<?php
if (!empty($_POST['username']) && !empty($_POST['pwd'])) {
include ('Push.php');
$push = new Push();
$user = $push->loginUsers($_POST['username'], $_POST['pwd']);
if(!empty($user)) {
$_SESSION['username'] = $user[0]['username'];
header("Location:index.php");
} else {
$loginError = "Invalid username or password!";
}
}
?>



Step3: Add Notification and Display List
In manage_notification.php file, we will create HTML for adding new notification by Administrator.

<div class="row">
<div class="col-sm-6">
<h3>Add New Notification:</h3>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<table class="table borderless">
<tr>
<td>Message</td>
<td><textarea name="msg" cols="50" rows="4" class="form-control" required></textarea></td>
</tr>
<tr>
<td>Broadcast time</td>
<td><select name="time" class="form-control"><option>Now</option></select> </td>
</tr>
<tr>
<td>Loop (time)</td>
<td><select name="loops" class="form-control">
<?php
for ($i=1; $i<=5 ; $i++) { ?>
<option value="<?php echo $i ?>"><?php echo $i ?></option>
<?php } ?>
</select></td>
</tr>
<tr>
<td>Loop Every (Minute)</td>
<td><select name="loop_every" class="form-control">
<?php
for ($i=1; $i<=60 ; $i++) { ?>
<option value="<?php echo $i ?>"><?php echo $i ?></option>
<?php } ?>
</select> </td>
</tr>
<tr>
<td>For</td>
<td><select name="user" class="form-control">
<?php
$user = $push->listUsers();
foreach ($user as $key) {
?>
<option value="<?php echo $key['username'] ?>"><?php echo $key['username'] ?></option>
<?php } ?>
</select></td>
</tr>
<tr>
<td colspan=1></td>
<td colspan=1></td>
</tr>
<tr>
<td colspan=1></td>
<td><button name="submit" type="submit" class="btn btn-info">Add Message</button></td>
</tr>
</table>
</form>
</div>
</div>


we will implement functionality to save new notifications to database table on form submit.
<?php
if (isset($_POST['submit'])) {
if(isset($_POST['msg']) and isset($_POST['time']) and isset($_POST['loops']) and isset($_POST['loop_every']) and isset($_POST['user'])) {
$msg = $_POST['msg'];
$time = date('Y-m-d H:i:s');
$loop= $_POST['loops'];
$loop_every=$_POST['loop_every'];
$user = $_POST['user'];
$isSaved = $push->saveNotification($msg,$time,$loop,$loop_every,$user);
if($isSaved) {
echo '* save new notification success';
} else {
echo 'error save data';
}
} else {
echo '* completed the parameter above';
}
}
?>



Now we will display list of add notifications.

<h3>Notifications List:</h3>
<table class="table">
<thead>
<tr>
<th>No</th>
<th>Next Schedule</th>
<th>Message</th>
<th>Remains</th>
<th>User</th>
</tr>
</thead>
<tbody>
<?php $a =1;
$notifList = $push->listNotification();
foreach ($notifList as $key) {
?>
<tr>
<td><?php echo $a ?></td>
<td><?php echo $key['notif_time'] ?></td>
<td><?php echo $key['notif_msg'] ?></td>
<td><?php echo $key['notif_loop']; ?></td>
<td><?php echo $key['username'] ?></td>
</tr>
<?php $a++; } ?>
</tbody>
</table>




Step4: Broadcast Notification
In notification.js file, we will create function showNotification() to make Ajax request to notification.php to get notification details for logged in user and execute notification.

function showNotification() {
if (!Notification) {
$('body').append('<h4 style="color:red">*Browser does not support Web Notification</h4>');
return;
}
if (Notification.permission !== "granted")
Notification.requestPermission();
else {
$.ajax({
url : "notification.php",
type: "POST",
success: function(data, textStatus, jqXHR) {
var data = jQuery.parseJSON(data);
if(data.result == true) {
var data_notif = data.notif;
for (var i = data_notif.length - 1; i >= 0; i--) {
var theurl = data_notif[i]['url'];
var notifikasi = new Notification(data_notif[i]['title'], {
icon: data_notif[i]['icon'],
body: data_notif[i]['msg'],
});
notifikasi.onclick = function () {
window.open(theurl);
notifikasi.close();
};
setTimeout(function(){
notifikasi.close();
}, 5000);
};
} else {
}
},
error: function(jqXHR, textStatus, errorThrown) {}
});
}
};



Then we will call function showNotification() to execute notification on every 20 seconds. When user logged in, it will make ajax request to check for logged in user and display notification message accordingly.

$(document).ready(function() {
showNotification();
setInterval(function(){ showNotification(); }, 20000);
});


Step5: Get Notification Details
In notification.php file, we will get logged in user's notification details and returned as json response as this file called by Ajax request.
<?php
SESSION_START();
include ('Push.php');
$push = new Push();
$array=array();
$rows=array();
$notifList = $push->listNotificationUser($_SESSION['username']);
$record = 0;
foreach ($notifList as $key) {
$data['title'] = $key['title'];
$data['msg'] = $key['notif_msg'];
$data['icon'] = 'https://phpzag.com/demo/push-notification-system-with-php-mysql-demo/avatar.png';
$data['url'] = 'https://phpzag.com';
$rows[] = $data;
$nextime = date('Y-m-d H:i:s',strtotime(date('Y-m-d H:i:s'))+($key['notif_repeat']*60));
$push->updateNotification($key['id'],$nextime);
$record++;
}
$array['notif'] = $rows;
$array['count'] = $record;
$array['result'] = true;
echo json_encode($array);
?>


Step6: Create Get and Set Push Notification functions
In Push.php file, we will create functions to perform push notification functionality like get notification details, save notification, update etc.
<?php
class Push{
private $host = 'localhost';
private $user = 'root';
private $password = '';
private $database = 'phpzag_demos';
private $notifTable = 'notif';
private $userTable = 'notif_user';
private $dbConnect = false;
public function __construct(){
if(!$this->dbConnect){
$conn = new mysqli($this->host, $this->user, $this->password, $this->database);
if($conn->connect_error){
die("Error failed to connect to MySQL: " . $conn->connect_error);
}else{
$this->dbConnect = $conn;
}
}
}
private function getData($sqlQuery) {
$result = mysqli_query($this->dbConnect, $sqlQuery);
if(!$result){
die('Error in query: '. mysqli_error());
}
$data= array();
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$data[]=$row;
}
return $data;
}
public function listNotification(){
$sqlQuery = 'SELECT * FROM '.$this->notifTable;
return $this->getData($sqlQuery);
}
public function listNotificationUser($user){
$sqlQuery = "SELECT * FROM ".$this->notifTable." WHERE username='$user' AND notif_loop > 0 AND notif_time <= CURRENT_TIMESTAMP()";
return $this->getData($sqlQuery);
}
public function listUsers(){
$sqlQuery = "SELECT * FROM ".$this->userTable." WHERE username != 'admin'";
return $this->getData($sqlQuery);
}
public function loginUsers($username, $password){
$sqlQuery = "SELECT id as userid, username, password FROM ".$this->userTable." WHERE username='$username' AND password='$password'";
return $this->getData($sqlQuery);
}
public function saveNotification($msg, $time, $loop, $loop_every, $user){
$sqlQuery = "INSERT INTO ".$this->notifTable."(notif_msg, notif_time, notif_repeat, notif_loop, username) VALUES('$msg', '$time', '$loop', '$loop_every', '$user')";
$result = mysqli_query($this->dbConnect, $sqlQuery);
if(!$result){
return ('Error in query: '. mysqli_error());
} else {
return $result;
}
}
public function updateNotification($id, $nextTime) {
$sqlUpdate = "UPDATE ".$this->notifTable." SET notif_time = '$nextTime', publish_date=CURRENT_TIMESTAMP(), notif_loop = notif_loop-1 WHERE id='$id')";
mysqli_query($this->dbConnect, $sqlUpdate);
}
}
?>


You can view the live demo from the Demo link and can download the full script from the Download link below.
Demo [sociallocker]Download[/sociallocker]

Komentar

  1. Sorry, the script works but push notification does not appear, what could be the reason?

    BalasHapus
  2. I have just checked and its working fine.
    When user will visit page, browser ask for notification permissions, if permission allowed then it will start displaying notifications to logged in user. For example in live demo, there a notification created for the username "phpzag". When user 'phpzag' will logged in, notification will be started displaying every 20 seconds. Please check live demo that just added with this tutorial. Thanks!

    BalasHapus
  3. Another question is how to alter the script to work on php 7.

    BalasHapus
  4. i am applying according to you but it showing some erroe in login page
    Notice: Undefined variable: loginError in C:\xampp\htdocs\push_notification\login.php on line 22

    BalasHapus
  5. Please download complete script, may be missing its initialization at the top of page to display error if any. Thanks1

    BalasHapus
  6. You can try it, I think it should work on PHP7 without any issue.

    BalasHapus

Posting Komentar

Postingan Populer