Improving php page for sending Notifications to Android Devices - php

It Send Notification to android devices registered in the mysql database. this is the php code i'm using. and it's working well as far as i can tell.
<?php
$con = mysql_connect("*******.*****.com","*******","*********");
mysql_select_db("*******",$con);
$result1 = mysql_query("SELECT Device_ID FROM Registered_Users") or die(mysql_error());
$api_key = "***************-***********";
$response["products"] = array();
while ($row = mysql_fetch_array($result1))
{
$reg_id = array($row['Device_ID']);
$registrationIDs = $reg_id;
$message = $_POST['msg'];
$url = 'https://android.googleapis.com/gcm/send';
$fields = array('registration_ids' => $registrationIDs,'data'
=> array( "message" => $message ),);
$headers = array('Authorization: key='
. $api_key,'Content-Type: application/json');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch);
curl_close($ch);
}
echo "success";
?>
my question is : how can i improve this code to get the best performance " results " possible ?

use this way........
<?php
$con = mysql_connect("*******.*****.com","*******","*********");
mysql_select_db("*******",$con);
$result1 = mysql_query("SELECT Device_ID FROM Registered_Users") or die(mysql_error());
while ($row = mysql_fetch_array($result1))
{
$reg_id[] = $row['Device_ID'];
//from this way you dont need to run function again and again......
}
$api_key = "***************-***********";
$response["products"] = array();
$registrationIDs = $reg_id;
$message = $_POST['msg'];
$url = 'https://android.googleapis.com/gcm/send';
$fields = array('registration_ids' => $registrationIDs,'data'
=> array( "message" => $message ),);
$headers = array('Authorization: key='
. $api_key,'Content-Type: application/json');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch);
curl_close($ch);
echo "success";
?>
this will increase code performance....may this will help you

You should send one curl request which includes an array of registration_ids. Doing this will use less resources as it only has to connect to Google's servers in one step rather than sending off several requests. You can just send one request to handle many notifications.
You should also be using something other than mysql_* to interact with your database, for example PDO:
<?php
$dbName = '*****';
$dbUsername = '*****';
$dbPassword = '*****';
$api_key = "***************-***********";
$url = 'https://android.googleapis.com/gcm/send';
$message = $_POST['msg'];
$pdo = new PDO('mysql:host=localhost;dbname=' . $dbName, $dbUsername, $dbPassword);
$stmt = $pdo->query("SELECT Device_ID FROM Registered_Users");
$dbResults = $stmt->fetchAll();
$stmt->closeCursor();
$regIds = array_map(function (array $dbResult) {
return $dbResult['Device_ID'];
}, $dbResults);
$fields = array(
'registration_ids' => $regIds,
'data' => array( "message" => $message ),
);
$headers = array(
'Authorization: key=' . $api_key,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
curl_close($ch);
echo "success";

Related

How can i set the title of my push notification in my php script?

This is my php script and I am sending the body and the title strings from my android app .Here I'm able to get the message body in my notification but not the title and even if I put;
$message = array(
'message' => $body,
'title' => 'This is my title',
'sound' => 1
);
This is also not working.
<?php
$body = $_POST["body"];
$title = $_POST["title"];
$inc_phone = $_POST["inc_phone"];
function send_notification ($tokens,$message)
{
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
'registration_ids' => $tokens,
'data' => $message
);
$headers = array(
'Authorization:key = AIzaSyAe9Qxx2URTyqXmf0mTheMq_ss_DOJaVQs ',
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
//Connect to the database
$host = "127.0.0.1";
$user = "rajhanssingh"; //Your Cloud 9 username
$pass = ""; //Remember, there is NO password by default!
$db = "fcm"; //Your database name you want to connect to
$port = 3306; //The port #. It is always 3306
$conn = mysqli_connect($host, $user, $pass, $db, $port);
//$conn = mysqli_connect("localhost","root","","fcm");
$sql = " Select token From utoken where phone_no='$inc_phone' ";
$result = mysqli_query($conn,$sql);
$tokens = array();
if(mysqli_num_rows($result) > 0 ){
while ($row = mysqli_fetch_assoc($result)) {
$tokens[] = $row["token"];
}
}
mysqli_close($conn);
$message = array(
'message' => $body,
'title' => $title,
'sound' => 1
);
$message_status = send_notification($tokens, $message);
echo $message_status;
?>
this worked for me
function send_push_notification($registrationIDs, $message) {
$GOOGLE_API_KEY = "AIzaSyCzr6K_W3ImYwVQ-vQyhFztDSmchkFjeGQ";
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIDs,
'data' => ['message' => $message, 'title' => 'Title' ]
);
$headers = array(
'Authorization: key=' . $GOOGLE_API_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
// echo $result;
}

foreach loop working only for first record of database in php

I am stuck in one condition in my code. I am sending gcm push notifications to multiple user from php. I am getting the reg id's from the database. In code I am using foreach loop to send notification. But I am not sure why it is sending the push notification to only one user not to the all user. if I remove the push notification code then it will show me all the reg ids from the database.
<?php
$host_name = "localhost";
$user_name = "xxxxxxx";
$user_pass = "xxxxx";
$db_name = "xxxxxx";
$conn=mysql_connect($host_name,$user_name,$user_pass);
if(!$conn) {
echo"could not connect:".mysql_error();
} else {
mysql_select_db($db_name,$conn);
}
$query = "select reg_id from property_register where reg_id != ''";
$result = mysql_query($query) or die(mysql_error());
foreach(mysql_fetch_array($result) as $r_id) {
$gcmRegID = $r_id[0];
echo $gcmRegID . "<br>";
$pushMessage = "New Property Posted in CPO";
if (isset($gcmRegID) && isset($pushMessage)) {
$gcmRegIds = array($gcmRegID);
$message = array("m" => $pushMessage);
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $gcmRegIds,
'data' => $message,
);
// Update your Google Cloud Messaging API Key
define("GOOGLE_API_KEY", "xxxxxxxxxxxxxxxxxxxxxxxxxxxx");
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
}
?>
In short foreach loop is sending the notification to the first user only not to all. If I remove the gcm code and do echo of foreach loop records its show me all
Thanks
You have a return in your foreach loop, this will cause the first pass through the foreach to fire the retrun call and never loop through another foreach. The return is not needed. Use the following code instead.
<?php
$host_name = "localhost";
$user_name = "xxxxxxx";
$user_pass = "xxxxx";
$db_name = "xxxxxx";
$conn=mysql_connect($host_name,$user_name,$user_pass);
if(!$conn) {
echo"could not connect:".mysql_error();
} else {
mysql_select_db($db_name,$conn);
}
$query = "select reg_id from property_register where reg_id != ''";
$result = mysql_query($query) or die(mysql_error());
foreach(mysql_fetch_array($result) as $r_id) {
$gcmRegID = $r_id[0];
echo $gcmRegID . "<br>";
$pushMessage = "New Property Posted in CPO";
if (isset($gcmRegID) && isset($pushMessage)) {
$gcmRegIds = array($gcmRegID);
$message = array("m" => $pushMessage);
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $gcmRegIds,
'data' => $message,
);
// Update your Google Cloud Messaging API Key
define("GOOGLE_API_KEY", "xxxxxxxxxxxxxxxxxxxxxxxxxxxx");
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
}
}
?>

GCM return error: field data must be a json array

When I using GCM, I got an error return as: field "data" must be a JSON array. Any one have some idea of how to solve it? Thank you.
There is first part of my code, parts of code are omitted:
<?php
$gcm_regid = array();
$gcm_data = array();
while ($row = mysql_fetch_array($result)) {
array_push($gcm_regid, $single_gcm_regid );
array_push($gcm_data , $notificationMessage);
}
?>
Here are the second part:
<?php
$url = 'https://android.googleapis.com/gcm/send';
$apiKey = '******************************';
$registrationIDs = $gcm_regid;
$data = $gcm_data;
$fields = array('registration_ids' => $registrationIDs,
'data' => $data);
//http header
$headers = array('Authorization: key=' . $apiKey,
'Content-Type: application/json');
//curl connection
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
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;
?>
Change from line 5 of your code
$message = $gcm_data;
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array("message" =>$message)
);
Use json_encode on your $fields object to return a JSON representation.
Look at the accepted answer here to see how it's used.

Invoke a php script as a new record inserted into db

I am just creating a web service for push notification. I Here is my code -
<?php
// gcm api KEY FOR PUSH NOTIFICATION
define( 'API_ACCESS_KEY', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ123456' );
// CONNECT DB
$dbhandle = mysql_connect("localhost", "admin", "admin") or die(mysql_error()) ;
$selected = mysql_select_db("bdname" ,$dbhandle) or die(mysql_error());
$query4=mysql_query("SELECT * FROM `table_name` ORDER BY id DESC LIMIT 0,1");
$row1=mysql_fetch_array($query4);
// static gcm registration id
$reg = 'APA91bF-A97EurJz7IlGFD85cBIWGPCJv7UhV1j19sp6nKEH-9He1GOZQ9ZPegqYmVw3q2OA-_XPpePQckr5o97s9wTTbzYjornXCOqcR3jmN1t1aHV8i4CfRZOWuBDXTixzA3JDnzleHVY3xCtHev8tG90ife05Pw';
$registrationIds = array($reg);
$title=$row1['title'];
$number=$row1['number'];
$id=$row1['id'];
$created_at=$row1['created_at'];
$mes1 = $id .',' . $title . ',' . $number .',' . $created_at;
$message = str_replace('""','',$mes1);
$mes = $message;
$message = array("price" => $mes);
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIds,
'data' => $message,
);
$headers = array(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo $result;
//}
mysql_free_result($query4);
mysql_close($dbhandle);
?>
I just want if any new row inserted into table, this script will automatic invoke and send notification on given gcm registration id. How can i do this. Is there any php function to do this??
Please help.
Thanks in advance.
Please use this php method to send GCM notification
function sendNotification( $apiKey, $registrationIdsArray, $messageData )
{
$headers = array("Content-Type:" . "application/json", "Authorization:" . "key=" . $apiKey);
$data = array(
'data' => $messageData,
'registration_ids' => $registrationIdsArray
);
$ch = curl_init();
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send" );
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($data) );
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
Refer these links for detailed tuts on GCM implementation with php
http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/
http://distriqt.com/post/1273

no notification on device but there is notification in app -Android push notifications

There is notification in my android app.....but i cant see any notifications on my device...
heres my code...
function androidnotify($deviceToken,$message,$app,$badge,$alerttype,$xyzid)
{
$apiKey = ".........";
$url = 'https://android.googleapis.com/gcm/send';
$regid[]=$deviceToken;
$registrationIDs = $regid;
$fields = array('registration_ids'=> $registrationIDs,
'data' => $message,
'badge'=> $badge,
'alerttype'=> $alerttype,
'xyzid' => $xyzid);
$headers = array('Authorization: key=' . $apiKey,
'Content-Type: application/json');
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch);
}
I need notification on my device too...what should i do....
you can get demo of GCM from this LINK
it's working with PHP code
here is a code of it
$registatoin_ids must be array of device token(push tokens) $message also must be array
define("GOOGLE_API_KEY","API_KEY");
class GCM {
//put your code here
// constructor
function __construct() {
}
/**
* Sending Push Notification
*/
public function send_notification($registatoin_ids, $message) {
// include config
include_once 'config.php';
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
/*echo $result/*."\n\n".json_encode($fields);*/
}
}
To send a GCM create object of GCM CLASS
$gcm = new GCM();
and you can send GCM like
$gcm->send_notification(DEVICE_TOKENS_AS_ARRAY, MESSAGE_AS_ARRAY);

Categories