GCM send message to all devices [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have a problem with GCM, I can't send a message to all devices.
This isn't the original code, but is my own version!
send_message.php:
<?php
if (isset($_POST["regId"]) && isset($_POST["message"])) {
//$regId = $_POST["regId"];
$message = $_POST["message"];
include './GCM.php';
$gcm = new GCM();
//$registatoin_ids = array($regId);
$message = array("price" => $message);
include_once 'db_functions.php';
$db = new DB_Functions();
$users = $db->getAllUsers();
if($users != false){
$no_of_users = mysql_num_rows($users);
}else{
$no_of_users = 0;
}
$i = 0;
while ($row = mysql_fetch_array($users)) {
$ids[$i] = $row["gcm_regid"];
$i++;
foreach ($ids as $value){
echo $value;
$registatoin_ids = $value;
json_encode($registatoin_ids);
$result = $gcm->send_notification($registatoin_ids, $message);
echo $result;
}
}
echo $value;
echo $registatoin_ids;
}
?>
GCM.php:
<?php
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;
}
}
?>
db_functions.php:
<?php
class DB_Functions {
private $db;
//put your code here
// constructor
function __construct() {
include_once './db_connect.php';
// connecting to database
$this->db = new DB_Connect();
$this->db->connect();
}
// destructor
function __destruct() {
}
/**
* Storing new user
* returns user details
*/
public function storeUser($name, $email, $gcm_regid) {
// insert user into database
$result = mysql_query("INSERT INTO gcm_users(name, email, gcm_regid, created_at) VALUES('$name', '$email', '$gcm_regid', NOW())");
// check for successful store
if ($result) {
// get user details
$id = mysql_insert_id(); // last inserted id
$result = mysql_query("SELECT * FROM gcm_users WHERE id = $id") or die(mysql_error());
// return user details
if (mysql_num_rows($result) > 0) {
return mysql_fetch_array($result);
} else {
return false;
}
} else {
return false;
}
}
/**
* Get user by email and password
*/
public function getUserByEmail($email) {
$result = mysql_query("SELECT * FROM gcm_users WHERE email = '$email' LIMIT 1");
return $result;
}
/**
* Getting all users
*/
public function getAllUsers() {
$result = mysql_query("select * FROM gcm_users");
return $result;
}
/**
* Check user is existed or not
*/
public function isUserExisted($email) {
$result = mysql_query("SELECT email from gcm_users WHERE email = '$email'");
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
// user existed
return true;
} else {
// user not existed
return false;
}
}
}
?>
The original code is from Ravi Tamada.

change send_message.php to the bellow code :
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
include_once 'db_functions.php';
if (isset($_GET["message"]) && isset($_GET["Number"])) {
$message = $_GET["message"];
$db = new DB_Functions();
$users = $db->getAllUsers();
$regIds = array();
while($row = mysql_fetch_array($users)) {
array_push($regIds,$row['gcm_regid']);
}
echo isset($users);
if ($users != false)
$no_of_users = mysql_num_rows($users);
else
$no_of_users = 0;
include_once './GCM.php';
$gcm = new GCM();
$message = array("message" => $message);
$result = $gcm->send_notification($regIds, $message);
echo $result;
}
?>

Related

Parse error: syntax error, unexpected '(', expecting '{' in C:\wamp\www\NewFirebase\Firebase.php on line 3

sent push notification using Firebase via PHP API.Parameter pass from the android and data get to push notification sent to android. Announcement get data from the database and its pass data in Firebase class and its sent to notification in android.in line 3 whats error i don't Know.
Announcement.php
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
// $full_name = $_POST['full_name'];
// $contact_number = $_POST['contact_number'];
require_once __DIR__ . '/firebase.php';
require_once __DIR__ . '/push.php';
$firebase = new Firebase();
$push = new Push();
$reg = $_GET['reg'];
$fdate = $_GET['fdate'];
$tdate = date('Y-m-d G:i:s');
//$tdate = date("2018-01-20");
print_r($tdate);
$date2 = strtotime("+1 day", strtotime($fdate));
$fdate1 = date("Y-m-d", $date2);
//print_r($fdate1);
require_once('Demo.php');
$sql = "select max(AnnounceDate) as announcedate from AnnouncementTable";
$stmt1 = sqlsrv_query($conn,$sql);
$result = array();
$result["announcement"] = array();
$result["success"] = 1;
$row = sqlsrv_fetch_array($stmt1,SQLSRV_FETCH_ASSOC);
$date1 = $row["announcedate"]->format('Y-m-d');
$marks = array();
$marks["announcedate"] = $row["announcedate"]->format('Y-m-d');
array_push($result["announcement"], $marks);
echo json_encode($result);
print_r($date1);
if ($date1 != $fdate){
$check = "select * from
AnnouncementTable
where
AnnounceDate between '$fdate1' and '$tdate';select token from Std_Reg where RegNo='$reg'";
$stmt = sqlsrv_query($conn,$check);
if(sqlsrv_has_rows($stmt) > 0){
while ($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC)){
$notiTitle = "Eurasian Infotech";
$clickEvent ="Announcement";
$notiMessage = $row["Title"];
$notiDescription = $row["Description"];
$regId = $row['token'];
$push->setTitle($notiTitle);
$push->setMessage($notiMessage);
$push->setClickevent($clickEvent);
$push->setAnnounce($notiDescription);
$json = '';
$response = '';
$json = $push->getPush();
$response = $firebase->send($regId,$json);
//sendNotification($notiTitle, $notiMessage,$reg,$date1);
echo "sucessfully added";
}
}else{
echo "error in sending request";
}
}else{
echo "Sent Notification";
}
}else{
echo 'error';
}
?>
Firebase.php
<?php
class Firebase(){
public function send($to,$message){
$fields = array(
'to' => $to,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
private function sendPushNotification($fields) {
require_once __DIR__ . '/config.php';
// Set POST variables
$url = 'https://fcm.googleapis.com/fcm/send';
$headers = array(
'Authorization: key=' . FIREBASE_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);
return $result;
}
}
?>
push.php
<?php
class Push{
private $title;
private $message;
private $date;
private $announce;
private $clickevent;
function _construct(){
}
public function setTitle($title){
}
public function setMessage($message){
}
public function setDate($date){
}
public function setAnnounce($announce){
}
public function setClickevent($clickevent){
}
public function getPush(){
$res = array();
$res['data']['title'] = $this->title;
$res['data']['message'] = $this->message;
$res['data']['date'] = $this->date('Y-m-d');
$res['data']['announce'] = $this->announce;
$res['data']['clickevent'] = $this->clickevent;
$res['data']['timestamp'] = date('Y-m-d G:i:s');
return $res;
}
}
?>

convert data to JSON array

i am trying to use the push notification in google cloud messages and i am passing an array om registration ids, but for some reason i got the following error:
Field "data" must be a JSON array: You have just invited to play 'Soccer'
this is the part that i am trying to pass:
"registred_ids":["APA91bF9itasGCSK8NbD9u5GJWnEmbWCdS0sEn_xxRVbVpfI0_3FKkvxVBr5xtdE26VZgOO8rCBpf4CaAzHUbMj7PmmDxqpdbWO6VBrPB8dW4CPqPovJbnB_p1Ha_fuwyf8SnOqgOFajK8HEdiZO65qUljO2wCuuDQ"]
not the code of the gcm is :
<?php
class GCM {
function __construct() {
}
/**
* Sending Push Notification
*/
public function send_notification($registatoin_ids, $message) {
// include config
include_once 'connection.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_IPRESOLVE, CURL_IPRESOLVE_V4 );
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;
}
}
?>
and the code which passing the registration ids is:
<?php
include 'response_process.php';
include 'gcm.php';
class CreateEvent implements ResponseProcess {
public function dataProcess($dblink)
{
$output = array();
$sport = $_POST["sport_type"];
$date = date("Y-m-d",strtotime(str_replace('/','-',$_POST["date"])));
$s_time =$_POST["s_time"];
$e_time = $_POST["e_time"];
$lon = $_POST["lon"];
$lat = $_POST["lat"];
$event_type = $_POST["event_type"];
$max_p = $_POST["max_participants"];
$sched = $_POST["scheduled"];
$gen = $_POST["gender"];
$min_age = $_POST["minAge"];
$manager = $_POST["manager"];
$query = "SELECT * FROM event WHERE (event.longtitude = '$lon' AND event.latitude = '$lat')
AND event.event_date = '$date' And ((event.start_time BETWEEN '$s_time' AND '$e_time') OR (event.end_time BETWEEN '$s_time' AND '$e_time'))";
//AND (event.start_time = '$s_time' AND event.end_time = '$e_time')
//check time and place of the event
$result_q = mysqli_query($dblink,$query) or die (mysqli_error($dblink));
if(!$result_q)
{
$output["flag"]= "select failed";
$output["msg"] = $result_q;
return json_encode($output);
}
//case date and time are available
else {
$no_of_rows = mysqli_num_rows($result_q);
if ($no_of_rows < 1) {
$output["flag"] = "success";
$output["msg"] = "insert event";
$result = mysqli_query($dblink, "INSERT into event(manager_id,kind_of_sport,event_date,start_time,end_time,longtitude,latitude,private,gender,min_age,max_participants,current_participants,scheduled,event_status)
VALUES ('$manager','$sport','$date','$s_time','$e_time','$lon','$lat','$event_type','$gen','$min_age','$max_p','1','$sched','1')") or die (mysqli_error($dblink));
if (!$result) {
$output["flag"] = "failed to create event";
// return (json_encode($output));
}
else{
if(isset($_POST["invitedUsers"])){
$query_id = "SELECT id From event WHERE event.event_date = '$date' and event.start_time = '$s_time' and event.end_time = '$e_time'";
$event_s_res = mysqli_query($dblink,$query_id) or die (mysqli_error($dblink));
if(!$event_s_res)
{
$output["flag"] = "failed";
$output["msg"] = "Event id not found";
}
else{
$row = mysqli_fetch_assoc($event_s_res);
$no_of_rows = mysqli_num_rows($event_s_res);
if($no_of_rows > 1 || $no_of_rows == 0)
{
$output["flag"] = "failed";
$output["msg"] = "Event id not found";
}
else{
$event_id = $row["id"];
$json = $_POST["jsoninvited"];
$json = json_decode($json);
$output["size_invited"] = count($json);
$query_users = "SELECT id,gcm_id From users WHERE ";
$i=0;
$size_of_param = (count($json));
foreach($json as $user) {
if ($i < $size_of_param - 1)
// add a space at end of this string
$query_users .= "users.mobile = '".$user."' or ";
else {
// and this one too
$query_users .= "users.mobile = '".$user."' ";
$output["users"][] = $user['mobile'];
}
$i++;
$output["index"]=$i;
}
$output["user_query"]= $query_users;
$event_user_s_res = mysqli_query($dblink,$query_users) or die (mysqli_error($dblink));
if(!$event_user_s_res)
{
$output["flag"] = "failed";
$output["msg"] = "user id not found";
}
$insert_query = "INSERT into attending (event_id,user_id,status) VALUES ";
$i=0;
$status = "deny";
$registration_ids = array();
while($row_user = mysqli_fetch_assoc($event_user_s_res))
{
$registration_ids[$i]=$row_user["gcm_id"];
if($i<$size_of_param - 1)
$insert_query .= "('" .$event_id. "','" .$row_user["id"]. "','" .$status. "'), ";
else
$insert_query .= "('".$event_id."','".$row_user["id"]."','".$status."') ";
$i++;
}
$insert_query_res = mysqli_query($dblink,$insert_query) or die (mysqli_error($dblink));
if(!$insert_query_res)
{
$output["flag"] = "failed";
$output["msg"] = "failed to insert to attending table";
}else{
$output["id_query"]= $insert_query;
$output["registred_ids"] = $registration_ids;
$output["msg"] = "success to insert into attending";
$gcm = new GCM();
$message = "You have just invited to play '".$sport."'";
$output["gcm_message"]=$message;
$gcm_res = $gcm->send_notification($registration_ids,$message);
$output["gcm_res"] = $gcm_res;
} //els of $insert_query_res
} //else of $no_of_rows > 1 || $no_of_rows == 0
} // else of $event_s_res
} //if isset($_POST["invitedUsers"]
} // if $result
} // if $no_of_rows < 1
else {
$output["flag"] = "failed";
$output["msg"] = "Place is already occupied in this time";
}
}
return json_encode($output);
}
}
Use this-
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => array("message" => $message),
);
It says the data field needs to be an array, but you are setting it to $message, which is a string, not an array.
Field "data" must be a JSON array: You have just invited to play 'Soccer'
This means the value passed in data node is not a json.
Encoding $message into json will fix the error.

My Webservices not working PHP/MYSQL/JSON

I have created web services but it is not working using cURL.
When I am using file_get_contents($request) it is working.
I want to call it using cURL
Server Input Code
<?php
require_once('config.php');
$posts = array();
/* require the user as the parameter */
if(isset($_GET['roll']) and isset($_GET['name']))
{
/* soak in the passed variable or set our own */
$roll = $_GET['roll']; //no default
$name = $_GET['name']; //no default
/* grab the posts from the db */
if($roll!="" and $name!="")
{
$query = "INSERT INTO STUDENT VALUES('$roll','$name')";
if(mysql_query($query,$dblink))
{
$posts[] = array('status'=>'Data Inserted');
}
else
{
$posts[] = array('status'=>'Not Inserted');
}
}
else
{
$posts[] = array('status'=>'Null Value sent');
}
/* disconnect from the db */
#mysql_close($db);
}
else
{
$posts[] = array('status'=>'Please check the arguments');
}
/* output in necessary format */
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));
?>
Server Output Code is
<?php
require_once('config.php');
/* require the user as the parameter */
$posts = array();
if(isset($_REQUEST['roll']))
{
$posts = array();
/* soak in the passed variable or set our own */
$roll = $_REQUEST['roll']; //no default
/* grab the posts from the db */
if($roll!="")
{
if($roll=="All")
{
$query = "SELECT * FROM STUDENT";
}
else
{
$query = "SELECT * FROM `STUDENT` WHERE roll = '$roll'";
}
$result = mysql_query($query,$dblink) or die('Errant query: '.$query);
if(!$result)
{
$posts[] = array('status'=>'Roll Not Found');
}
else
{
/* create one master array of the records */
if(mysql_num_rows($result))
{
while($post = mysql_fetch_assoc($result))
{
$posts[] = array('student'=>$post);
}
}
else
{
$posts[] = array('status'=>'Roll not Found');
}
}
}
else
{
$posts[] = array('status'=>'Roll Should Not be Null');
}
/* disconnect from the db */
#mysql_close($db);
}
else
{
$posts[] = array('status'=>'Please send Valid Argument');
}
/* output in necessary format */
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));
?>
Call Using file_get_contents($request) Its working
<?php
$request="https://returns.jabong.com/tracking/WebServices/server_output.php?roll=12MCA02";
//$request="https://returns.jabong.com/tracking/WebServices/server_input.php?roll=12MCA02&name=Aneesh Khan";
$response = file_get_contents($request);
print_r($response);
?>
Call using cURL - Its not working
$sUrl = "https://returns.jabong.com/tracking/WebServices/server_input.php";
$sData = 'roll=12MCA05&name=Aneesh A Khan';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sUrl);
curl_setopt($ch, CURLOPT_POSTFIELDS, $sData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$vRes = curl_exec($ch);
curl_close($ch);
header('Content-Type: text/json');
echo $vRes;
?>
Call is not working using cURL , Please help me soon ?
Your code was quite mixed up - you are requiring $_GET parameters in some places, $_REQUEST parameters in others and the curl function looks like it's attempting to send via POST - but there are options missing to force curl to send via POST. Using a simple GET request via curl with the parameters appended to the url the data gets inserted.
<?php
$sUrl = "https://returns.jabong.com/tracking/WebServices/server_input.php";
$sData = 'roll='.uniqid().'&name='.uniqid('user_',true);
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $sUrl . '?' . $sData );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
$vRes = curl_exec($ch);
curl_close($ch);
echo $vRes;
?>
Which method is it you want to use? And, as #Marc pointed out this code is open to sql injection.

Memory Leak or Connection not closed

I am having three files index.php, DB_Function, DB_Connect to connect through mysql server. But response is very slow and task is almost running according to the hosting server people.
index.php
if (isset($_POST['tag']) && $_POST['tag'] != '') {
// get tag
$tag = $_POST['tag'];
// include db handler
require_once 'DB_Functions.php';
$db = new DB_Functions();
// response Array
$response = array("tag" => $tag, "success" => 0, "error" => 0);
// check for tag type
if ($tag == 'login') {
// Request type is check Login
$email = $_POST['email'];
$password = $_POST['password'];
// check for user
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false) {
// user found
// echo json with success = 1
$uservalue= $user["userid"];
$usercal = $db->getUserByuserid($uservalue);
if ($usercal != false) {
$response["usercal"]["userid"] = $usercal["userid"];
$response["usercal"]["newcalorie"] = $usercal["newcalorie"];
$response["usercal"]["oldcalorie"] = $usercal["oldcalorie"];
$response["usercal"]["flag"] = $usercal["flag"];
$response["usercal"]["fat"] = $usercal["fat"];
$response["usercal"]["carbohydrate"] = $usercal["carbohydrate"];
$response["usercal"]["protein"] = $usercal["protein"];
$response["usercal"]["startdate"] = $usercal["startdate"];
$response["usercal"]["enddate"] = $usercal["enddate"];
$response["usercal"]["createddate"] = $usercal["createddate"];
$response["usercal"]["updateddate"] = $usercal["updateddate"];
$response["usercal"]["createdby"] = $usercal["createdby"];
$response["usercal"]["updatedby"] = $usercal["updatedby"];
}
$response["success"] = 1;
$response["user"]["userid"] = $user["userid"];
$response["user"]["fname"] = $user["fname"];
$response["user"]["email"] = $user["email"];
$response["user"]["altemail"] = $user["altemail"];
$response["user"]["age"] = $user["age"];
$response["user"]["gender"] = $user["gender"];
$response["user"]["weight"] = $user["weight"];
$response["user"]["unit"] = $user["unit"];
$response["user"]["height"] = $user["height"];
$response["user"]["weightgoal"] = $user["weightgoal"];
$response["user"]["activitylevel"] = $user["activitylevel"];
$response["user"]["exerciselevel"] = $user["exerciselevel"];
$response["user"]["disease"] = $user["disease"];
$response["user"]["createddate"] = $user["createddate"];
$response["user"]["updateddate"] = $user["updateddate"];
$response["user"]["createdby"] = $user["createdby"];
$response["user"]["updatedby"] = $user["updatedby"];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}
}
else {
echo "Access Denied";
}
?>
DB_Function.php
<?php
class DB_Functions {
private $db;
//put your code here
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$this->db = new DB_Connect();
$this->db->connect();
}
// destructor
function __destruct() {
}
/**
* Get user by email and password
*/
public function getUserByEmailAndPassword($email, $password) {
$result = mysql_query("SELECT * FROM userDetails WHERE email = '$email' AND password = '$password'") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
return $result;
} else {
// user not found
return false;
}
}
/**
* Get user by email and password
*/
public function getUserByuserid($uservalue) {
$result = mysql_query("SELECT * FROM CalorieInfo WHERE userid= '$uservalue' ") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
return $result;
} else {
$calresult = mysql_query("INSERT INTO CalorieInfo( userid,startdate, createddate, updateddate,createdby,updatedby) VALUES('$uservalue' ,NOW(), NOW(), NOW(),'$uservalue','$uservalue')");
if ($calresult) {
$id = mysql_insert_id();
$calresult = mysql_query("SELECT * FROM CalorieInfo WHERE id = $id");
return mysql_fetch_array($calresult);
}else{
// user not found
return false;
}
}
}
?>
DB_Connect.php
<?php
class DB_Connect {
// constructor
function __construct() {
//this->connect();
}
// destructor
function __destruct() {
//closing db
}
// Connecting to database
public function connect() {
require_once 'config.php';
// connecting to mysql
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die(mysql_error());
// selecting database
mysql_select_db(DB_DATABASE) or die(mysql_error());
// return database handler
return $con;
}
// Closing database connection
public function close() {
mysql_close();
}
}
?>
Is there anything more optimized that i should be aware of ?
Is something missing in my code. Hosting people says that tomcat and mysql is consuming more task.
Here are my recommendations
1.- Always close the connection after retrieving the data.
2.- If you are expecting just one row for a query like this
"SELECT * FROM userDetails WHERE email = '$email' AND password = '$password'
you should add LIMIT 1 at the end of the query for retrieving the only possible row
3.-Add indexes to the table
4.-Test your performance with mysqlslap

Gcm message not sent to more that 1000 users

Gcm message not sent to more that 1000 users , gcm has its own limit of sending message to 1000 users so the idea is to divide the users in batch of 1000 each i tried that but the gcm message is received by first 1000 users only how can we send the message in batches of 1000 each, in a total of say 5000 users, so that all users get the message i am new to php please explain the working
<?php
require 'connect.php';
function sendPushNotification($registration_ids, $message) {
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registration_ids,
'data' => $message,
);
define('GOOGLE_API_KEY', 'xxxxxxxxxxxxxxxxxxxxxxxxx');
$headers = array(
'Authorization:key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
//echo json_encode($fields);
$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_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if($result === false)
die('Curl failed ' . curl_error());
curl_close($ch);
return $result;
}
$pushStatus = '';
function getGCMCount(){
$total = "";
$query = "SELECT count(gcm_regId) as total FROM gcm_users";
while($query_row = mysql_fetch_assoc($query_run)) {
$total = $query_row['total'] / 1000;
}
return $total;
}
if(!empty($_GET['push'])) {
$query = "SELECT gcm_regId FROM gcm_users";
if($query_run = mysql_query($query)) {
$gcmRegIds = array();
$i = 0;
while($query_row = mysql_fetch_assoc($query_run)) {
$i++;
$gcmRegIds[floor($i/1000)][] = $query_row['gcm_regId'];
//echo $i . "</br>" ;
}
}
$pushMessage = $_POST['message'];
if(isset($gcmRegIds) && isset($pushMessage)) {
$pushStatus = array();
//echo "</br> counnt of messages send is". count($pushStatus);
foreach($gcmRegIds as $key=>$val)
{
$message = array('price' => $pushMessage);
//$message1 = array($key=>$val);
//$c = (array_merge($message ,$message1 ));
$pushStatus[] = sendPushNotification($val, $message);
//echo $key;
}
}
}
?>
<html>
<head>
<title>Google Cloud Messaging (GCM) Server in PHP</title>
</head>
<body>
<h1>Google Cloud Messaging (GCM) Server in PHP</h1>
<form method = 'POST' action = 'send_all.php/?push=1'>
<div>
<textarea rows = 2 name = "message" cols = 23 placeholder = 'Messages to Transmit via GCM'></textarea>
</div>
<div>
<input type = 'submit' value = 'Send Push Notification via GCM'>
</div>
<p><h3><?php //echo $pushStatus . "<br>"?></h3></p>
</form>
</body>
</html>
Refer this snippet for sending messages to more than 1000 users
<?php
//Sample for sending notification to more than 1000 users
$mPushNotification = $push->getMessage();
$stmt = $this->con->prepare("SELECT gcm_regid FROM gcm_users");
$stmt->execute();
$result = $stmt->get_result();
$tokens = array();
while ($token = $result->fetch_assoc()) {
array_push($tokens, $token['gcm_regid']);
}
$firebase = new Firebase();
$total = count($tokens);
$groups = ceil($total/800);
$currentval=ceil($total/$groups);
$firebase = new Firebase();
for ($i=0; $i <$groups; $i++) {
$val=($i*$currentval)+1;
$total = ($i+1)*$currentval;
$resToken = getSpecificToken($val,$total);
$result1 = $firebase->send($resToken, $mPushNotification);
}
function getSpecificToken($upper,$lower)
{
$stmt = $this->con->prepare("SELECT * FROM gcm_users LIMIT $upper,$lower");
$stmt->execute();
$result = $stmt->get_result();
$tokens = array();
while ($token = $result->fetch_assoc()) {
array_push($tokens, $token['gcm_regid']);
}
return $tokens;
}
function getMessage() {
$res = array();
$res['data']['id'] = 1;
$res['data']['title'] = "TestTitle";
$res['data']['message'] = "TestMessage : Hello";
return $res;
}
?>
//Firebase File
<?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 actual 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;
}
}
?>

Categories