In our previous tutorial, we have explained how to Build Content Management System with PHP & MySQL. In this tutorial, we will explain How To Develop Push Notification System with PHP and 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.
Also, read:
- Build Content Management System with PHP & MySQL
- Build Live Chat System with Ajax, PHP & MySQL
- Build Comment System with Ajax, PHP & 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 will also like these tutorials:
- Star Rating System with Ajax, PHP and MySQL
- Create Event Calendar with jQuery, PHP and MySQL
- Build Your Own CAPTCHA Script with PHP
- Create Bootstrap Cards with PHP and MySQL
- Build Content Management System with PHP & MySQL
- Convert Unix Timestamp To Readable Date Time in PHP
- Ajax Drop Down Selection Data Load with PHP & MySQL
- Inventory Management System with Ajax, PHP & MySQL
- Drag and Drop File Upload using jQuery and PHP
- Load Dynamic Content in Bootstrap Popover with Ajax, PHP & MySQL
- Create Live Editable Table with jQuery, PHP and MySQL
- Live Add Edit Delete datatables Records with Ajax, PHP and MySQL
You can view the live demo from the Demo link and can download the full script from the Download link below.
Demo Download
Sorry, the script works but push notification does not appear, what could be the reason?
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!
Cool. Everything works fine. The error was that used the http Protocol, and it is necessary https. Thank you!!!
Alex,
Thanks!
the time difference,
how to set the time for my country?
Another question is how to alter the script to work on php 7.
You can try it, I think it should work on PHP7 without any issue.
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
Please download complete script, may be missing its initialization at the top of page to display error if any. Thanks1
Very Helpful script. Thanks for sharing it’s working perfectly.
The code is insecure and is not properly using MySQLi.
Thanks for suggestion, I will try to update to make it more secure.
Hi beautiful example, it works great! I wanted to ask you, is there a way to show notifications when the web page is not open but only the browser is started?
I will try to handle this in same tutorial. thanks!
Muito bom o código, funcionou perfeito no computador, mas no celular ele não notifica
Eu estou olhando para consertá-lo por telefone. Obrigado!
Very good code, it worked perfect on the computer, but on the phone it does not notify
We will try to check issue and fix. Thanks!
Hello,
First of all, very nice code & explanation
I have same issue as above, have you guys fixed it yet?
Thank you
Very nice script, easy to adjust for my needs, Thank for your time and work PHPZAG TEAM 🙂
How can I show the notificacion to an a specific user when it’s selected from a form and storaged in a DB?
You need to done change to make handle this as per requirement to send notification to that user. You need to done changes to get that user from database.
nc work
Thanks!
Where is index.php and logout.php file?
You need to download project zip file for all files. thanks!
OK, all of my messages showed up…. almost 40 of them LOL.
It was my fault, I have 4 monitors and the page I had opened trying to get messages was on a sub level monitor [meaning not the main one]. As soon as I moved the page to my main PC monitor, they came flooding in…
Sorry about this! It works fantastic.
Thank you
Great tutorial but difficult to understand for new programmers, try indenting and inline-code comments to explain what those function does and if possible reduce the need for use of class. Keep up the Great Work!
Notification works but keeps showing thousands of notifications even after disabling notifications for the site. It’s very annoying and bugging. How do I fix this?
Can you share your code to fix issue. Thanks!
Using PHP code helps to reduce the number of blocks and plugins. After the push notification is created, you need to schedule them for sending relevant notifications. I believe that using a plugin does it more effectively and easily in this case. But many push services use JS code, which can increase the page load time. Thanks for providing this snippet.
Hi and thank you for doing the tutorial.
I’m getting the following error when I try to login with the standard details.
“Warning: Use of undefined constant MYSQL_ASSOC – assumed ‘MYSQL_ASSOC’ (this will throw an Error in a future version of PHP) in C:\xampp\htdocs\pns-db\Push.php on line 26
Warning: mysqli_fetch_array() expects parameter 2 to be int, string given in C:\xampp\htdocs\pns-db\Push.php on line 26”
Any help would be appreciated.
Try to use MYSQLI_ASSOC instead of MYSQLI_ASSOC, it may fixed the error. thanks!
what apache and mysql extensions or modules does this need? i put in a live web server and it’s not working. the notifications do not send out / popup. what do i need to check?
it’s working on latest PHP. you can try on your local server first before moving to live server. thanks!
Hi and very very thanks sir doing this tutorial,
sir, I’m getting this error
“Warning: Use of undefined constant MYSQL_ASSOC – assumed ‘MYSQL_ASSOC’ (this will throw an Error in a future version of PHP) in C:\xampp\htdocs\notifications\Push.php on line 26″
I changed MYSQL_ASSOC to MYSQLI_ASSOC
then login success
but notification is not working
I’m trying to add a notification
nothing will happen
any help sir
thank you PHPZAG TEAM
Try to debug code, may be there any error. you can also check notification settings in your browser. thanks!
hi!
your code works. but can not display push notifications in Android phones.
It’s not working in mobile devices yet, I will update about this, thanks!
Is there any tutorials for when the page is not opened but the notification will still arrive, cause this one now i think it only works when the page is opened
Currently, there is only one tutorial about push notification, thanks!