PHP Files
·
Config.php
<?php
define('DB_USERNAME','your user name');
define('DB_PASSWORD','your password');
define('DB_NAME','your database name');
define('DB_HOST','localhost');
//defined a new constant for firebase api key
define('FIREBASE_API_KEY', ‘YOUR_SERVER_KEY');
·
DbConnect.php
<?php
//Class DbConnect
class DbConnect
{
//Variable to store
database link
private $con;
//Class constructor
function
__construct()
{
}
//This method will
connect to the database
function connect()
{
//Including the
config.php file to get the database constants
include_once
dirname(__FILE__) . '/Config.php';
//connecting to
mysql database
$this->con =
new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
//Checking if
any error occured while connecting
if (mysqli_connect_errno())
{
echo
"Failed to connect to MySQL: " . mysqli_connect_error();
}
//finally
returning the connection link
return
$this->con;
}
}
·
DbOperation.php
<?php
class
DbOperation
{
//Database connection link
private $con;
//Class constructor
function __construct()
{
//Getting the DbConnect.php file
require_once dirname(__FILE__) .
'/DbConnect.php';
//Creating a DbConnect object to
connect to the database
$db = new DbConnect();
//Initializing our connection link of
this class
//by calling the method connect of
DbConnect class
$this->con = $db->connect();
}
//storing token in database
public function
registerDevice($email,$token){
if(!$this->isEmailExist($email)){
$stmt =
$this->con->prepare("INSERT INTO devices (email, token) VALUES (?,?)
");
$stmt->bind_param("ss",$email,$token);
if($stmt->execute())
return 0; //return 0 means success
return 1; //return 1 means failure
}else{
return 2; //returning 2 means email
already exist
}
}
//the method will check if email already
exist
private function isEmailexist($email){
$stmt =
$this->con->prepare("SELECT id FROM devices WHERE email = ?");
$stmt->bind_param("s",$email);
$stmt->execute();
$stmt->store_result();
$num_rows = $stmt->num_rows;
$stmt->close();
return $num_rows > 0;
}
//getting all tokens to send push to all
devices
public function getAllTokens(){
$stmt =
$this->con->prepare("SELECT token FROM devices");
$stmt->execute();
$result = $stmt->get_result();
$tokens = array();
while($token =
$result->fetch_assoc()){
array_push($tokens,
$token['token']);
}
return $tokens;
}
//getting a specified token to send push to
selected device
public function getTokenByEmail($email){
$stmt =
$this->con->prepare("SELECT token FROM devices WHERE email =
?");
$stmt->bind_param("s",$email);
$stmt->execute();
$result =
$stmt->get_result()->fetch_assoc();
return array($result['token']);
}
//getting all the registered devices from
database
public function getAllDevices(){
$stmt =
$this->con->prepare("SELECT * FROM devices");
$stmt->execute();
$result = $stmt->get_result();
return $result;
}
}
?>
·
Firebase.php
<?php
class
Firebase {
public function send($registration_ids,
$message) {
$fields = array(
'registration_ids' =>
$registration_ids,
'data' => $message,
);
return
$this->sendPushNotification($fields);
}
/*
* This function will make the actuall curl
request to firebase server
* and then the message is sent
*/
private function sendPushNotification($fields)
{
//importing the constant files
require_once 'Config.php';
//firebase server url to send the curl
request
$url = 'https://fcm.googleapis.com/fcm/send';
//building headers for the request
$headers = array(
'Authorization: key=' .
FIREBASE_API_KEY,
'Content-Type: application/json'
);
//Initializing curl to open a
connection
$ch = curl_init();
//Setting the curl url
curl_setopt($ch, CURLOPT_URL, $url);
//setting the method as post
curl_setopt($ch, CURLOPT_POST, true);
//adding headers
curl_setopt($ch, CURLOPT_HTTPHEADER,
$headers);
curl_setopt($ch,
CURLOPT_RETURNTRANSFER, true);
//disabling ssl support
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,
false);
//adding the fields in json format
curl_setopt($ch, CURLOPT_POSTFIELDS,
json_encode($fields));
//finally executing the curl request
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' .
curl_error($ch));
}
//Now close the connection
curl_close($ch);
//and return the result
return $result;
}
}
?>
·
GetRegisteredDevices.php
<?php
require_once 'DbOperation.php';
$db = new DbOperation();
$devices = $db->getAllDevices();
$response = array();
$response['error'] = false;
$response['devices'] = array();
while($device = $devices->fetch_assoc()){
$temp = array();
$temp['id']=$device['id'];
$temp['email']=$device['email'];
$temp['token']=$device['token'];
array_push($response['devices'],$temp);
}
echo json_encode($response);
?>
·
Push.php
<?php
class Push {
//notification title
private $title;
//notification message
private $message;
//notification image url
private $image;
//initializing values in this constructor
function __construct($title, $message,
$image) {
$this->title = $title;
$this->message = $message;
$this->image = $image;
}
//getting the push notification
public function getPush() {
$res = array();
$res['data']['title'] =
$this->title;
$res['data']['message'] = $this->message;
$res['data']['image'] =
$this->image;
return $res;
}
}
?>
·
RegisterDevice.php
<?php
require_once 'DbOperation.php';
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
$token = $_POST['token'];
$email = $_POST['email'];
$db = new DbOperation();
$result = $db->registerDevice($email,$token);
if($result == 0){
$response['error'] = false;
$response['message'] = 'Device registered
successfully';
}elseif($result == 2){
$response['error'] = true;
$response['message'] = 'Device already
registered';
}else{
$response['error'] = true;
$response['message']='Device not registered';
}
}else{
$response['error']=true;
$response['message']='Invalid Request...';
}
echo json_encode($response);
?>
·
SendMultiplePush.php
<?php
//importing
required files
require_once
'DbOperation.php';
require_once
'Firebase.php';
require_once
'Push.php';
$db = new
DbOperation();
$response =
array();
if($_SERVER['REQUEST_METHOD']=='POST'){
//hecking the required params
if(isset($_POST['title']) and
isset($_POST['message'])) {
//creating a new push
$push = null;
//first check if the
push has an image with it
if(isset($_POST['image'])){
$push = new
Push(
$_POST['title'],
$_POST['message'],
$_POST['image']
);
}else{
//if the
push don't have an image give null in place of image
$push = new
Push(
$_POST['title'],
$_POST['message'],
null
);
}
//getting the push from
push object
$mPushNotification =
$push->getPush();
//getting the token from
database object
$devicetoken =
$db->getAllTokens();
//creating firebase
class object
$firebase = new
Firebase();
//sending push
notification and displaying result
echo $firebase->send($devicetoken,
$mPushNotification);
}else{
$response['error']=true;
$response['message']='Parameters
missing';
}
}else{
$response['error']=true;
$response['message']='Invalid
request';
}
echo
json_encode($response);
·
SendSinglePush.php
<?php
//importing
required files
require_once
'DbOperation.php';
require_once
'Firebase.php';
require_once
'Push.php';
$db = new
DbOperation();
$response =
array();
if($_SERVER['REQUEST_METHOD']=='POST'){
//hecking the required params
if(isset($_POST['title']) and
isset($_POST['message']) and isset($_POST['email'])){
//creating a new push
$push = null;
//first check if the push has an image with it
if(isset($_POST['image'])){
$push = new Push(
$_POST['title'],
$_POST['message'],
$_POST['image']
);
}else{
//if the push don't have an image give null in
place of image
$push = new Push(
$_POST['title'],
$_POST['message'],
null
);
}
//getting the push from push object
$mPushNotification = $push->getPush();
//getting the token from database object
$devicetoken =
$db->getTokenByEmail($_POST['email']);
//creating firebase class object
$firebase = new Firebase();
//sending push notification and displaying
result
echo $firebase->send($devicetoken,
$mPushNotification);
}else{
$response['error']=true;
$response['message']='Parameters missing';
}
}else{
$response['error']=true;
$response['message']='Invalid request';
}
echo
json_encode($response);