Tuesday, June 26, 2018

Send push notification to multiple android devices using PHP & MySQL

Guys before starting this matter first create database and table then after that put 'server api key' (API_ACCESS_KEY) in PHP script, all the steps mentioned in the below.

How database & table looks I have updated screenshot just below


<?php
$con = mysqli_connect('localhost','root','','ottoedge');
if(!$con) die('Connection failed') . mysqli_connect_error();

$result = mysqli_query($con, "SELECT email, token FROM devices") or die('Unable to get FCM IDs' . mysqli_error($con));
$tokens = array();

while($row = mysqli_fetch_array($result)){
 $tokens[] = $row['token'];
}

#API access key from Google API's Console
define( 'API_ACCESS_KEY', 'AAAAfdCHJl8:APA91bFtHiNBibXcMVY9or0JCr2R15ez6jiAEpyt0tMVWdNu_AWin8sexxc5RLfJHW6VdZOce_2-QHvsmaPL5oAZPOYpJVnadFeL5kpM0eD6bzOyWI6kUdClum765xLNTN5ZukslsiRKS');

$registrationIds = $tokens;

#prep the bundle
     $msg = array(
  'body'  => 'Your notification for test drive reminder!',
  'title' => 'Alarm!',
              'icon' => 'myicon',/*Default Icon*/
               'sound' => 'mySound'/*Default sound*/
          );

$fields = array(
     'registration_ids' => $registrationIds,
     'notification' => $msg
);
$headers = array(
     'Authorization: key=' . API_ACCESS_KEY,
     'Content-Type: application/json'
);

#Send Reponse To FireBase Server
  $ch = curl_init();
  curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
  curl_setopt( $ch,CURLOPT_POST, true );
  curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
  curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
  curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
  curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
  $result = curl_exec($ch );
  curl_close( $ch );
#Echo Result Of FireBase Server
echo $result;

?>

No comments:

Post a Comment