SPONSORS

Faster PHP Cloud Hosting
2380 views · 263 days ago

![Implement Web Push Notification in PHP using W3C provided Notification API](https://images.ctfassets.net/vzl5fkwyme3u/ERmW7y6S781gcWIiFjTRn/de1c1aeb3c79093210828760fc373ab2/AdobeStock_152541972.png?w=1000)

Hi Guys,

I am sharing you the simple steps by which you can broadcast the web push notifications to your subscriber. In this tutorial we are making a subscriber form and saving information using Ajax and PHP and then through a server side code returning response to current logged in user and showing notification to that user.

**Following are the steps to build this system**

#### 1. Create a database, I am creating db with name 'web_notifications'

Creating subscribers and notifications tables using following sql statements

```

CREATE TABLE IF NOT EXISTS `subscribers` (

`id` int(11) NOT NULL,

`name` varchar(255) NOT NULL,

`email` varchar(255) NOT NULL,

`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP

) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `subscribers`

ADD PRIMARY KEY (`id`);

ALTER TABLE `subscribers`

MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

CREATE TABLE IF NOT EXISTS `notifications` (

`id` int(11) NOT NULL,

`to_user` int(11) NOT NULL,

`title` varchar(255) NOT NULL,

`body` varchar(255) NOT NULL,

`url` varchar(255) NOT NULL,

`is_sent` int(11) NOT NULL DEFAULT '0',

`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP

) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `notifications`

ADD PRIMARY KEY (`id`);

ALTER TABLE `notifications`

MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

```

#### 2. Now create a db_connect.php file with following code

```

<?php

session_start();

$servername = "localhost";

$username = "root";

$password = "";

$dbname = "web_notifications";

/ / Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

/ / Check connection

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

}

?>

```

#### 3. Create a cookies.js file to read and write browser cookies

```

function WriteCookie(key,content) {

var now = new Date();

now.setMonth( now.getMonth() + 1 );

document.cookie = key+"=" + escape(content) + ";";

document.cookie = "expires=" + now.toUTCString() + ";"

}

function ReadCookie(key) {

var allcookies = document.cookie;

cookiearray = allcookies.split(';');

var CookieData=Array();

for(var i=0; i<cookiearray.length; i++) {

k = cookiearray[i].split('=')[0];

v = cookiearray[i].split('=')[1];

CookieData[k]=v;

}

return CookieData[key];

}

```

#### 4. Create a ajax file to read and mark is_sent if any notification foun to be sent in database for that user. create file with name 'fetch_notifications.php' with following content

```

<?php require 'db_connect.php';

$sql = "SELECT id,title,body,url FROM notifications where to_user='"[email protected]$_GET['user_id']."' and is_sent='0' ";

$result = $conn->query($sql);

$data=array();

if ($result->num_rows > 0) {

while($row = $result->fetch_assoc()) {

$data[]=$row;

/ /update this record as is_sent

$upd = "update notifications set is_sent='1' where id='".$row['id']."' ";

$conn->query($upd);

}

}

if(count($data)>0)

{

$response=array("status"=>1,"notification"=>$data);

}

else

{

$response=array("status"=>0,"error"=>"No new notification!");

}

echo json_encode($response);

$conn->close();

?>

```

#### 5. Now code index.php to show subscriber form and on submit insert record into the subscriber table

```

<?php require 'db_connect.php'; ?>

<!DOCTYPE html>

<html>

<head>

<title>Web Push Notification Demo</title>

<script src="./cookies.js" type="text/javascript"></script>

<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">

<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous">

<?php

if(isset($_POST['subscribe_form']))

{

$_SESSION['is_login']=0;

$username=$conn->real_escape_string($_POST['username']);

$useremail=$conn->real_escape_string($_POST['useremail']);

$sql = "INSERT INTO subscribers set name='".$username."',email='".$useremail."' ";

if ($conn->query($sql) === TRUE) {

$_SESSION['is_login']=1;

$_SESSION['Uid']= $conn->insert_id;

$_SESSION['Uname']= $username;

?>

<script type="text/javascript">

WriteCookie("Uid","<?php echo $_SESSION['Uid']; ?>");

</script>

<?php

$msg="<p style='color:green'>You have subscribe for push notification succesfully :)</p>";

} else {

$msg="<p style='color:red'>Error in subscribing for notifications</p>";

}

}

?>

<div class="container">

<?php

if(isset($msg) && $msg!='')

{

?>

<br>

<div class="alert alert-info">

<?php echo $msg; ?>

</div>

<?php

}

if(isset($_SESSION['is_login']) && $_SESSION['is_login']==1)

{

?>

<h2>Welcome <?php echo $_SESSION['Uname']; ?></h2>

<script type="text/javascript">

setInterval(function(){

check_notification();

}, 10000);

function check_notification()

{

var Uid=ReadCookie("Uid");

if(Uid!==undefined)

{

$.ajax({url: "fetch_notifications.php?user_id="+Uid, success: function(result){

var response=JSON.parse(result);

if(response.status==1)

{

response=response.notifications;

for (var i = response.length - 1; i >= 0; i--) {

var url = response[i]['url'];

var noti = new Notification(response[i]['title'], {

icon: 'logo.png',/ /this should be your logo in root folder

body: response[i]['body'],

});

noti.onclick = function () {

window.open(url);

noti.close();

};

};

}

else{

console.log(response.error);

}

}

});

}

}

</script>

<?php

}

else

{

?>

<h2 class="text-center">Subscribe for Notifications</h2>

<div class="row justify-content-center">

<div class="col-12 col-md-8 col-lg-6 pb-5">

<div class="card border-primary rounded-0">

<div class="card-header p-0">

<div class="bg-info text-white text-center py-2">

<h3><i class="fa fa-envelope"></i> Information</h3>

<p class="m-0">provide your information</p>

</div>

</div>

<div class="card-body p-3">

<form method="post">

<!--Body-->

<div class="form-group">

<div class="input-group mb-2">

<div class="input-group-prepend">

<div class="input-group-text"><i class="fa fa-user text-info"></i></div>

</div>

<input type="text" class="form-control" id="username" name="username" placeholder="Input Your Name Here" required>

</div>

</div>

<div class="form-group">

<div class="input-group mb-2">

<div class="input-group-prepend">

<div class="input-group-text"><i class="fa fa-envelope text-info"></i></div>

</div>

<input type="text" class="form-control" id="useremail" name="useremail" pattern="[^@\s][email protected][^@\s]+\.[^@\s]+" title="Invalid email address" placeholder="[email protected]" required>

</div>

</div>

<div class="text-center">

<input type="submit" value="Subscribe" name="subscribe_form" class="btn btn-info btn-block rounded-0 py-2">

</div>

</form>

</div>

</div>

</div>

</div>

<?php }?>

</div>

</head>

<body>

</body>

</html>

<?php

$conn->close();

?>

```

The frontend of your subscription page (index.php) should look like this:

![Subscribing Form to User](https://www.w3school.info/blogimages/front_web_push_page.png)

Now we are ready to receive notification in frontend, but we still need to create an admin page from where we can send notification to subscriber(s).

#### 6. Create a table for admin user

```

CREATE TABLE IF NOT EXISTS `admin` (

`id` int(11) NOT NULL,

`username` varchar(255) NOT NULL,

`password` varchar(255) NOT NULL,

`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP

) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `admin`

ADD PRIMARY KEY (`id`);

ALTER TABLE `admin`

MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

INSERT INTO `web_notifications`.`admin` (`id`, `username`, `password`, `createdAt`) VALUES (NULL, 'admin', MD5('123456'), CURRENT_TIMESTAMP);

```

Following is the code for admin.php to add the notifications to subscriber(s) account also i have inserted following login credentials for admin in admin table:

username:admin

password:123456

#### 7. Now put following code in admin.php

```

<?php require 'db_connect.php'; ?>

<!DOCTYPE html>

<html>

<head>

<title>ADMIN PAGE</title>

<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">

<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous">

<?php

if(isset($_POST['login']))

{

$_SESSION['admin_login']=0;

$username=$conn->real_escape_string($_POST['username']);

$password=$conn->real_escape_string($_POST['password']);

$sql = "SELECT * FROM admin where username='".$username."' and password='".md5($password)."' ";

$result = $conn->query($sql);

if ($result->num_rows > 0) {

$_SESSION['admin_login']=1;

$msg="<p style='color:green'>Admin Logged-in Successfully :)</p>";

}

else {

$msg="<p style='color:red'>INVALID CREDENTIALS FOR ADMIN</p>";

}

}

if(isset($_POST['add_notification']))

{

$title=$conn->real_escape_string($_POST['title']);

$body=$conn->real_escape_string($_POST['body']);

$url=$conn->real_escape_string($_POST['url']);

$users=$_POST['users'];

foreach ($users as $user_id) {

$ins = "insert into notifications set to_user='".$user_id."' , title='".$title."', url='".$url."', body='".$body."' ";

$conn->query($ins);

}

$msg="<p style='color:green'>Notification(s) added to subscribers account.</p>";

}

?>

<div class="container">

<?php

if(isset($msg) && $msg!='')

{

?>

<br>

<div class="alert alert-info">

<?php echo $msg; ?>

</div>

<?php

}

if(isset($_SESSION['admin_login']) && $_SESSION['admin_login']==1)

{

?>

<h2>Welcome Admin, Send notification to Subscriber(s)</h2>

<form method="post">

<div class="form-group">

<label for="sel1">Select Subscriber(s):</label>

<select multiple="multiple" required="required" class="form-control" id="users" name="users[]">

<?php

$sql = "SELECT id,name FROM subscribers";

$result = $conn->query($sql);

$data=array();

if ($result->num_rows > 0) {

while($row = $result->fetch_assoc()) {

echo "<option value='".$row['id']."'>".$row['name']."</option>";

}

}

?>

</select>

</div>

<div class="form-group">

<label for="email">Title</label>

<input type="text" required class="form-control" placeholder="notification title here" name="title" id="title">

</div>

<div class="form-group">

<label for="email">Message</label>

<textarea required class="form-control" placeholder="notification message here" name="body" id="body"></textarea>

</div>

<div class="form-group">

<label for="email">Url</label>

<input type="url" required class="form-control" placeholder="notification landing/click url here" name="url" id="url">

</div>

<input type="submit" class="btn btn-primary btn-block" name="add_notification" value="Submit" />

</form>

<?php

}

else

{

?>

<h2 class="text-center">ADMINISTRATOR</h2>

<div class="row justify-content-center">

<div class="col-12 col-md-8 col-lg-6 pb-5">

<div class="card border-primary rounded-0">

<div class="card-header p-0">

<div class="bg-info text-white text-center py-2">

<h3><i class="fa fa-envelope"></i> LOGIN</h3>

<p class="m-0">provide admin login credentials</p>

</div>

</div>

<div class="card-body p-3">

<form method="post">

<!--Body-->

<div class="form-group">

<div class="input-group mb-2">

<div class="input-group-prepend">

<div class="input-group-text"><i class="fa fa-user text-info"></i></div>

</div>

<input type="text" class="form-control" id="username" name="username" placeholder="Input username here" required>

</div>

</div>

<div class="form-group">

<div class="input-group mb-2">

<div class="input-group-prepend">

<div class="input-group-text"><i class="fa fa-key text-info"></i></div>

</div>

<input type="password" class="form-control" id="password" name="password" placeholder="your password here" required>

</div>

</div>

<div class="text-center">

<input type="submit" value="Login" name="login" class="btn btn-info btn-block rounded-0 py-2">

</div>

</form>

</div>

</div>

</div>

</div>

<?php }?>

</div>

</head>

<body>

</body>

</html>

<?php

$conn->close();

?>

```

The admin page will ask login credentials first then it will look like following screenshot:

![Admin Send Notifiv=cation to subscribers](https://www.w3school.info/blogimages/admin_web_push_page.png)

Now in your project if you open index.php you have a frontend where user will register themselves to receive notifications, and admin.php is your backend where you can send notifications to users or subscribers

If you face any problem in setup this small project please just let me know in the comments below, or by messaging me.

SPONSORS

Faster PHP Cloud Hosting