I have 100000 users, I am always sending information, in fact this information don't reach to all users and I don't know why.
I will attach the send php files, and please see if you can tell what is wrong with this and which logic I should use. Note if I change 1000 number to 3000 no user receive also I don't know why.
<?php include('session.php');?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<?php
header('Content-type: text/html; charset=utf-8');
//generic php function to send GCM push notification
function sendPushNotificationToGCM($registatoin_ids, $message) {
//Google cloud messaging GCM-API url
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
define("GOOGLE_API_KEY", "my_key");
$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));
//curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
?>
<?php
header('Content-type: text/html; charset=utf-8');
$response = array();
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
if (isset($_GET['level']) &&isset($_GET['m1']) &&isset($_GET['m2']) &&isset($_GET['m3']) &&isset($_GET['m4']) &&isset($_GET['m5']) &&isset($_GET['m6']) &&isset($_GET['m7'])){
$level=$_GET['level'];
$m1=$_GET['m1'];
$m2=$_GET['m2'];
$m3=$_GET['m3'];
$m4=$_GET['m4'];
$m5=$_GET['m5'];
$m6=$_GET['m6'];
$m7=$_GET['m7'];
$m11=mysql_real_escape_string($_GET['m1']);
$m21=mysql_real_escape_string($_GET['m2']);
$m31=mysql_real_escape_string($_GET['m3']);
$m41=mysql_real_escape_string($_GET['m4']);
$m51=mysql_real_escape_string($_GET['m5']);
$m61=mysql_real_escape_string($_GET['m6']);
$m71=mysql_real_escape_string($_GET['m7']);
mysql_query("SET NAMES 'utf8'");
$resultaa = mysql_query("INSERT words (id, level, m1, m2, m3, m4, m5, m6, m7) VALUES (NULL,'$level','$m11','$m21','$m31','$m41','$m51','$m61','$m71')");
$id = mysql_insert_id();
if($level == 0){
$result = mysql_query("SELECT Rid FROM users ");
}else{
$result = mysql_query("SELECT Rid FROM users where level = '$level' OR level = '4'");
//$result = mysql_query("SELECT Rid FROM users where level = '$level'");
}
$message = array(
'word_id' => $id,
'm1' => $m1,
'm2' => $m2,
'm3' => $m3,
'm4' => $m4,
'm5' => $m5,
'm6' => $m6,
'm7' => $m7,
'level' => $level
);
if (mysql_num_rows($result) > 0) {
for($counter = 0; $counter<mysql_num_rows($result) ; $counter+=1000) {
$gcmRegIds=array();
for($counter2=$counter ; $counter2<$counter+1000;$counter2++){
if($counter2<mysql_num_rows($result)){
$row = mysql_fetch_array($result);
$gcmRegIds[]=$row["Rid"];
}
}
$pushStatus = sendPushNotificationToGCM($gcmRegIds, $message);
echo $pushStatus;
}
$time = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];
echo "Process Time: {$time}";
}else {
$response["success"] = 0;
$response["message"] = "No user found";
echo json_encode($response);
}
//echo $result;
}
else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
</body>
</html>
Related
I am using PHP to send GCM notification to users. Based on their token saved in SQL on server. But I have a limit of 1000 notifications at once to send,
this is my working code , now i need to edit it to loop the process, and send 5000 notification in sections, 1000 than 1000 etc.
Here is my PHP code, and a simple HTML I didn't post here,
<?php
$mysqlHost = "";
$mysqlUser = "";
$mysqlPwd = ";
$mysqlDbname = "";
class GCM {
function __construct(){}
public function send_notification($registatoin_ids,$data) {
// GOOGLE API KEY
define("GOOGLE_API_KEY","************");
$url="https://android.googleapis.com/gcm/send";
$fields=array(
"registration_ids"=>$registatoin_ids,
"data"=>$data,
);
//var_dump($fields);
$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_VERIFYPEER,false);
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($fields));
$result_gcm=curl_exec($ch);
if($result_gcm===FALSE){
die("Curl failed: ".curl_error($ch));
}
curl_close($ch);
//echo $result_gcm;
}
}
// Create connection
$conn = mysqli_connect($mysqlHost, $mysqlUser, $mysqlPwd, $mysqlDbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$result = $conn->query("SELECT * FROM users WHERE users_android_token IS NOT NULL AND users_android_token <> ''");
$android_tokens = array();
$x=0;
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$android_tokens[] = $row["users_android_token"];
$x++;
}
} else {
echo "0 results";
}
$conn->close();
$title = $_POST['title'];
$msg = $_POST['message'];
$link = $_POST['link'];
if ($android_tokens != array()) {
$gcm=new GCM();
$data=array("title"=>$title,"description"=>$msg,"link"=>$link);
$result_android=$gcm->send_notification($android_tokens,$data);
}
?>
Rather than send notification by registrationId, why not using send notification by topic. You only need to make client subscribed to certain topic.
in GCM, you can send notification topic with this code :
function send_notification_topic($topicname, $message){
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'to' => '/topics/' . $topicname,
'data' => $message
);
$headers = array(
'Authorization: key=AIzablablablayourServerKey',
'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;
}
Use this code for divided your tokens .
if ($android_tokens != array()) {
$gcm = new GCM();
$data = array("title" => $title,"description" => $msg,"link" => $link);
//Divide array into 1000 tokens
$splitTokens = array_chunk($android_tokens, 1000);
//loop the array
//Obs: for looping notification may push slow
foreach($splitTokens as $tokens) {
$result_android = $gcm -> send_notification($tokens,$data);
}
}
For divide GCM may push the notification slow . it take up to 2 - 10 mins.
i am using following code to send gcm message using php and mysqldb i have successfully send the gcm message and received it on the device however the android guidelines state that gcm message should be send in batch of 1000 each http://developer.android.com/training/cloudsync/gcm.html#multicast
now my question is how can we send gcm messages in lots of 1000 to a database of say 10,000 registered users.
<?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', 'keys_value');
$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 = '';
if(!empty($_GET['push'])) {
$query = "SELECT gcm_regId FROM gcm_users";
if($query_run = mysql_query($query)) {
$gcmRegIds = array();
while($query_row = mysql_fetch_assoc($query_run)) {
array_push($gcmRegIds, $query_row['gcm_regId']);
}
}
$pushMessage = $_POST['message'];
if(isset($gcmRegIds) && isset($pushMessage)) {
$message = array('price' => $pushMessage);
$pushStatus = sendPushNotification($gcmRegIds, $message);
}
}
?>
<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 ?></h3></p>
</form>
</body>
</html>
Make $gcmRegIds to be a 2D array and then foreach it to push msg:
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'];
}
}
$pushMessage = $_POST['message'];
if(isset($gcmRegIds) && isset($pushMessage)) {
$message = array('price' => $pushMessage);
$pushStatus = array();
foreach($gcmRegIds as $val) $pushStatus[] = sendPushNotification($val, $message);
}
}
Here is what i did for my scenario to resolve for FCM .You can also ignore some parts of the code
<?php
$saved_tokens=array(); // could be more than 1000 token the maximum size as per google FCM requirement
//$count=1;
$ID_SETS = array_chunk($saved_tokens, 1000); // make a group of 1000 items in each set
foreach ($ID_SETS as $value_ids) {
// echo "Chunk ".$count."<br>";
sendFCM_Notification("what_ever_parameter_data",$value_ids);
foreach ($value_ids as $value_i ) { // you can remove this part its not neccessary
//echo " ---- contents of Chunk ".$count ."with Value".$value_i."<br>";
}
// $count++;
}
function sendFCM_Notification($what_ever_parameter,$reg_ids_array){
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
'registration_ids' => $reg_ids_array,
'data' => $what_ever_parameter
);
$headers = array(
'Authorization:key = YOUR_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;
}
?>
i am trying to send the gcm message everything works fine the message is send from server and received in the phone , i am testing the code to send it to more than 1000 users so i am concatenating the count to each message however it just sends 1 as count and not actual count
how can i send the count in gcm messages
i am trying this for testing and i am totally new to php
<?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', 'gcmcode');
$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 = '';
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();
$j = 0;
foreach($gcmRegIds as $val)
{$j++;
$message = array('price' => $j . $pushMessage);
$pushStatus[] = sendPushNotification($val,$message);
}
}
}
?>
<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 ?></h3></p>
</form>
</body>
</html>
You can call the count method of mysql which returns the total row count. I implemented a simple sample, do as you required.
$query = "SELECT count(gcm_regId) as total FROM gcm_users";
while($query_row = mysql_fetch_assoc($query_run)) {
$total = $query_row['total'] / 1000;
}
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;
}
function sendPushNotification($registration_ids, $message) {
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registration_ids,
'data' => $message . " " . getGCMCount(),
);
define('GOOGLE_API_KEY', 'gcmcode');
$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;
}
I am sending a GCM push message (less then 1000) with:
$Regids = mysql_query("SELECT regid FROM $tabel WHERE active = '1'");
$result_array = array();
while ($row = mysql_fetch_array($Regids)){
$result_array[] = $row['regid'];
}
$headers = array(
'Content-Type:application/json',
'Authorization:key=' . $serverApiKey
);
$data = array(
'registration_ids' => $result_array,
'data' => array(
'type' => 'New',
'title' => 'LH',
'msg' => ''.$msj.''
)
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
if ($headers)
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$result = curl_exec($ch);
curl_close($ch);
When I print the $result to check (and use for updating the database) it shows:
{"multicast_id":000,"success":274,"failure":75,"canonical_ids":13,"results":[{"message_id":"123"},{"message_id":"123"},{"error":"NotRegistered"},{"error":"NotRegistered"},{"message_id":"123"},{"message_id":"123"},{"registration_id":"456","message_id":"123"}]}
There is no },{ between every (canonical) registration_id and the next (success) message_id or error.
(I shortened the response to make it readable)
So my update part fails
$result = json_decode($result);
for ($i = 0; $i < count($result->{'results'}); $i++) {
if ($result->{'results'}[$i]->{'message_id'}) {
...
} elseif($result->{'results'}[$i]->{'error'}) {
...
} elseif ($result->{'results'}[$i]->{'registration_id'}) {
...
}
}
Does someone know what's wrong?
The format of the response you got is correct . A message for which you get a canonical registration id is still accepted by Google and is therefore successful , and that's why you get a message id in addition to the canonical registration id for that message . That's why there are no brackets after the canonical registration id.
I am using PHP. I want to fetch all gmail contacts of a user, i am using a PHP code that is calling google API through CURL. But, when i am doing this on localhost, it is doing well and giving me all contacts.
But when i am doing this on online server that server in US, it is giving me response "Account Disabled" and also receiving a security mail by same user from google.
i am using below code :
function getGmailContacts($user, $password) {
//========================================== step 1: login ===========================================================
$login_url = "https://www.google.com/accounts/ClientLogin";
$fields = array(
'Email' => $user,
'Passwd' => $password,
'service' => 'cp', // <== contact list service code
'source' => 'test-google-contact-grabber',
'accountType' => 'GOOGLE',
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,$login_url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS,$fields);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
$returns = array();
foreach (explode("\n",$result) as $line)
{
$line = trim($line);
if (!$line) continue;
list($k,$v) = explode("=",$line,2);
$returns[$k] = $v;
}
curl_close($curl);
//echo "<pre>";
//print_r($returns);exit;
if(!isset($returns['Error'])) {
//========================== step 2: grab the contact list ===========================================================
$feed_url = "http://www.google.com/m8/feeds/contacts/$user/full?alt=json&max-results=250";
$header = array(
'Authorization: GoogleLogin auth=' . $returns['Auth'],
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $feed_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
$data = json_decode($result, true);
//echo "<pre>";
//print_r($data);exit;
$contacts = array();
$i=0;
foreach ($data['feed']['entry'] as $entry)
{
//echo $i." ";
$entryElement = $entry;
if(isset($entryElement['gd$email'])) {
$gdEmailData = $entryElement['gd$email'][0];
//$contact->title = $entryElement['title']['$t'];
//$contact->email = $gdEmailData['address'];
$contacts[$gdEmailData['address']] = $entryElement['title']['$t'];
}
}
//var_dump($contacts);
//print_r($contacts);
return $contacts;
}
else {
if($returns['Error']=='BadAuthentication') {
//echo '<strong>User Name and Password is incorrect.</strong>';
$errorArr = array("Error"=>"User Name and Password is incorrect.");
//print_r($errorArr);
return $errorArr;
}
}
}
That mail contains that
"Someone recently tried to use an application to sign in to your
Google Account....Location: New York NY, New York, United States....."
.
I thing this error is occurring from location change.
can any one help me please? Thanks in advance.