I'm in big trouble that I have no idea what it can be.
I have an APP that has more than 100k users on the table, I happen to call the GCM service inside LOOP after about 1 minute presents this error message.
I have treated all the fields so as not to be NULL, I do not know what it can be!
Will it be timeout from ajax?
The call in GCM is as follows:
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'data' => array(
"mensagem" => $message
),
'registration_ids' => $registatoin_ids
);
if (is_array($data)) {
foreach ($data as $key => $value) {
$fields['data'][$key] = $value;
}
}
$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_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);
Loop to bring the database id-------------
for ($i = 0; $i < $num / 1000; $i++)
{
$query = $con->query("SELECT gcm_regid from registration where status ='S' and LENGTH(gcm_regid) = 152 and app_id=$Id_Aplicativo LIMIT $current_num,1000");
foreach($query as $data)
{
if (!is_null($data["gcm_regid"]))
{
$row[] = is_null($data["gcm_regid"]) ? " " : $data["gcm_regid"];
$cont = $cont + 1;
}
}
// print_r($row);
$pushStatus = send_notification($con, $row, $mensagem, array(
'titulo' => is_null($titulo) ? " " : $titulo, //$titulo,
'sub_mensagem' => is_null($sub_mensagem) ? " " : $sub_mensagem, //$sub_mensagem,
'content_mensagem' => is_null($content_mensagem) ? " " : $content_mensagem, //$content_mensagem,
'content_info' => is_null($content_info) ? " " : $content_info, //$content_info,
'url_imagem' => is_null($path . $nome_imagem) ? " " : $path . $nome_imagem, //$path.$nome_imagem,// Esse Path vem do arquivo Conect.php
'url_audio' => is_null($path_audio . $filenameAudio) ? " " : $path_audio . $filenameAudio, //$path_audio.$filenameAudio, // Esse Path vem do arquivo Conect.php
'tipo_notificacao' => is_null($TipoNotificacao) ? " " : $TipoNotificacao, //$TipoNotificacao
));
$row = null;
$current_num+= 1000;
}
404 Not Found Nginx/1.12.0
Related
I am building cron job with API calls in loop for DB entries and Have performance issues.
Particularly in this part:
if (!empty($sudCode) && !empty($sudBroj) && isset($sudCode) && isset($sudBroj)) {
// echo $sudCode . "<br>";
// echo $sudBroj . "<br>";
$epredmet = ePredmeti($sudCode, $sudBroj);
// print_r($epredmet);
// echo "<br>";
if (isset($epredmet["data"]["prvi"]["lastUpdateTime"])) {
$lastUpdateTime = $epredmet["data"]["prvi"]["lastUpdateTime"];
$dateTime = str_replace("T", " ", $lastUpdateTime);
echo $nas . " - " . $dateTime . "<br>";
}
}
on line:
if (isset($epredmet["data"]["prvi"]["lastUpdateTime"])) {
I have few Databases and on one when this line is reached sever goes to 504 Gateway Time-out after 2 minutes.
Hosting company said that it goes in timeout because Apache web server waits for PHP parser to process data, what ever that means.
What is strange, is if I leave out that if check i script finishes and I get results but with Notice: Trying to access array offset on value of type null in
because I expect that $epredmet after API call looks like this:
- array(1) { ["data"]=> array(1) { ["prvi"]=> NULL } } // case not found
- array(1) { ["data"]=> array(1) { ["prvi"]=> array(1) { ["lastUpdateTime"]=> NULL } } } // case found but lastUpdateTime is not set, null
- array(1) { ["data"]=> array(1) { ["prvi"]=> array(1) { ["lastUpdateTime"]=> string(23) "2021-06-14T22:51:22.171" } } } // case found and lastUpdateTime is set
So what I need to do is filter out just last case where lastUpdateTime is set, and all that I read is suggesting to solve it with isset but that breaks my script for some reason.
PHP V 7.4
Please advise.
Im attaching full script in case someone notices problem somewhere else:
function eSudovi()
{
$endpoint = "xxx";
$qry = '{"query":"query{sudovi {id, sudNaziv}}"}';
$headers = array();
$headers[] = 'Content-Type: application/json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $qry);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
$eSudovi = eSudovi()["data"]["sudovi"];
function findSudCode($val, $eSudovi)
{
foreach ($eSudovi as $key => $value) {
if ($value["sudNaziv"] == $val) {
return $value["id"];
}
}
}
function ePredmeti($sud, $pred)
{
$endpoint = "xxx";
$qry = '{"query":"query{ prvi:predmet(sud: ' . $sud . ', oznakaBroj: \"' . $pred . '\") {lastUpdateTime}}"}';
$headers = array();
$headers[] = 'Content-Type: application/json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $qry);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
$results = mysqli_query($con, "
SELECT DISTINCT predf_nas_br, predf_odv, predf_SUD, predf_SUDBROJ
FROM PREDMETIFView
WHERE predf_SUD <> '' AND predf_SUDBROJ <> '' AND predf_SUDBROJ NOT LIKE '% %'
UNION ALL
SELECT DISTINCT predp_nas_br, predp_odv, predp_SUD, predp_SUDBROJ
FROM PREDMETIPView
WHERE predp_SUD <> '' AND predp_SUDBROJ <> '' AND predp_SUDBROJ NOT LIKE '% %'
;");
while ($row = $results->fetch_assoc()) {
foreach ($row as $key => $value) {
if ($key == "predf_nas_br") {
$nas = $value;
}
if ($key == "predf_SUD") {
$sud = trim($value);
if (!empty($sud) && isset($sud)) {
$sudCode = findSudCode($sud, $eSudovi);
}
};
if ($key == "predf_SUDBROJ") {
$sudBroj = trim($value);
};
if (!empty($sudCode) && !empty($sudBroj) && isset($sudCode) && isset($sudBroj)) {
// echo $sudCode . "<br>";
// echo $sudBroj . "<br>";
$epredmet = ePredmeti($sudCode, $sudBroj);
print_r($epredmet);
echo "<br>";
if (isset($epredmet["data"]["prvi"]["lastUpdateTime"])) {
$lastUpdateTime = $epredmet["data"]["prvi"]["lastUpdateTime"];
$dateTime = str_replace("T", " ", $lastUpdateTime);
echo $nas . " - " . $dateTime . "<br>";
}
}
}
};
// preg_match('/\s/', $sudBroj)
Edit:
I also tried this:
if (isset($epredmet["data"]["prvi"]["lastUpdateTime"]) && !empty($epredmet["data"]["prvi"]["lastUpdateTime"])) {
and this:
if (isset($epredmet["data"]["prvi"]) && !empty($epredmet["data"]["prvi"])) {
if (isset($epredmet["data"]["prvi"]["lastUpdateTime"]) && !empty($epredmet["data"]["prvi"]["lastUpdateTime"])) {
Same thing, it hangs, but without it all it work with erros.
Something like this would do to reuse the curl handle (note: haven't had time to test it, but you'll get the idea).
class ePredmeti{
public $epredmet;
private $curl,$ini_opt;
function __construct(){
$endpoint ='xxx';
$headers = ['Content-Type: application/json'];
$timeout = 30;
$this->curl= curl_init();
$this->ini_opt=[
CURLOPT_URL => $endpoint,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_CONNECTTIMEOUT => $timeout,
CURLOPT_TIMEOUT => $timeout
];
}
public function _exec($sud, $pred){
$start=microtime(true);
$this->epredmet = null;
$query_opt=[
CURLOPT_POSTFIELDS=>
'{"query":"query{ prvi:predmet(sud: ' . $sud . ', oznakaBroj: \"' . $pred . '\") {lastUpdateTime}}"}'
];
curl_reset($this->curl);
curl_setopt_array($this->curl, $this->ini_opt);
curl_setopt_array($this->curl, $query_opt);
$ret = curl_exec($ch);
if (!curl_errno($this->curl)){
if(curl_getinfo($this->curl, CURLINFO_HTTP_CODE)!==200){
echo 'HTTP error: '.$http_code.'<br>';
}
else{
$this->epredmet = json_decode($ret,true);
}
}
else{
echo curl_error($this->curl).'<br>';
}
echo 'Took: '.(microtime(true)-$start).'<br>';
}
}
before the while() put something like:
$mycurl = new ePredmeti();
and instead of $epredmet = ePredmeti($sudCode, $sudBroj); use
$mycurl->_exec($sudCode, $sudBroj);
Finally, instead of if (isset($epredmet["data"]["prvi"]["lastUpdateTime"])) { you can use
if( isset($mycurl->epredmet["data"]["prvi"]["lastUpdateTime"]) ) {
The last one works because the class returns null on any error and isset() checks if a variable exists and is not null.
after user fill form of his or her information it create some sessions that i need kill all sessions in callback page but it dont work by destroy sessions or unset sessions.
after fill information page we have 3 pages as bellow.
payment.php
<?php session_start();
require_once('variables.php');
require_once('../includes/config.php');
$stmt = $db->prepare('SELECT * FROM order_main WHERE name = :name and phone=:phone');
if($stmt->execute(array(':name' => $_SESSION['post-data']['name'], ':phone' => $_SESSION['post-data']
['phone'] ) ));
while($row = $stmt->fetch()){
//if($code == $row['code']){
//if(!empty($_POST['code'])){
$_SESSION['order_id'] = $row['order_id'];
//}
// }
}
$order_id = $_SESSION['order_id'];
$amount = $_SESSION['total'];
echo $_SESSION['order_id'];
$_SESSION['order_id']=3;
echo $_SESSION['post-data']['name'];
echo $_SESSION['post-data']['order_desc'];
$name = $_SESSION['post-data']['name'];
$phone = $_SESSION['post-data']['phone'];
$order_desc = $_SESSION['post-data']['order_desc'];
$params = array(
'order_id' => $order_id ,
'amount' => 10000,
'phone' => $phone,
'name' => $name,
'desc' => $order_desc,
'callback' => URL_CALLBACK,
);
idpay_payment_create($params);
/**
* #param array $params
* #return bool
*/
function idpay_payment_create($params) {
$header = array(
'Content-Type: application/json',
'X-API-KEY:' . APIKEY,
'X-SANDBOX:' . SANDBOX,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, URL_PAYMENT);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result);
if (empty($result) || empty($result->link)) {
print 'Exception message:';
print '<pre>';
print_r($result);
print '</pre>';
return FALSE;
}
//.Redirect to payment form
header('Location:' . $result->link);
}
variables.php
<?php session_start();
define('URL_CALLBACK', 'http://www.siteaddress.org/blog/php-simple-master/callback.php');
define('URL_PAYMENT', 'https://api.idpay.ir/v1.1/payment');
define('URL_INQUIRY', 'https://api.idpay.ir/v1.1/payment/inquiry');
define('URL_VERIFY', 'https://api.idpay.ir/v1.1/payment/verify');
define('APIKEY', 'xxxxx...');
define('SANDBOX', 1);
callback.php(i want destroy some or all sessions here but cant)
<?php session_start();
require_once('variables.php');
require_once('config.php');
?>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$response = $_POST;
}
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$response = $_GET;
}
if (empty($response['status']) ||
empty($response['id']) ||
empty($response['track_id']) ||
empty($response['order_id'])) {
return FALSE;
}
if ($response['status'] != 10) {
print idpay_payment_get_message($response['status']);
}
// if $response['id'] was not in the database return FALSE
$inquiry = idpay_payment_get_inquiry($response);
if ($inquiry) {
$verify = idpay_payment_verify($response);
}
/**
* #param array $response
* #return bool
*/
function idpay_payment_get_inquiry($response) {
$header = array(
'Content-Type: application/json',
'X-API-KEY:' . APIKEY,
'X-SANDBOX:' . SANDBOX,
);
$params = array(
'id' => $response['id'],
'order_id' => $response['order_id'],
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, URL_INQUIRY);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result);
if (empty($result) ||
empty($result->status)) {
print 'Exception message:';
print '<pre>';
print_r($result);
print '</pre>';
return FALSE;
}
if ($result->status == 10) {
return TRUE;
}
print idpay_payment_get_message($result->status);
return FALSE;
}
/**
* #param array $response
* #return bool
*/
function idpay_payment_verify($response) {
$header = array(
'Content-Type: application/json',
'X-API-KEY:' . APIKEY,
'X-SANDBOX:' . SANDBOX,
);
$params = array(
'id' => $response['id'],
'order_id' => $response['order_id'],
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, URL_VERIFY);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result);
if (empty($result) ||
empty($result->status)) {
print 'Exception message:';
print '<pre>';
print_r($result);
print '</pre>';
return FALSE;
}
print idpay_payment_get_message($result->status);
//print '<pre>';
//print_r($result);
//print '</pre>';
$stmt = $db->prepare('UPDATE order_main SET track_id = :track_id, id = :id, order_date=:date
WHERE order_id = :order_id ') ;
$stmt->execute(array(
':track_id' => $_GET['track_id'],
':id' => $_GET['id'],
':date' => $_GET['date'],
':order_id' => $_GET['order_id']
));
}
/**
* #param int $status
* #return string
*/
function idpay_payment_get_message($status) {
switch ($status) {
case 1:
return 'پرداخت انجام نشده است';
case 2:
return 'پرداخت ناموفق بوده است';
case 3:
return 'خطا رخ داده است';
case 10:
return 'در انتظار تایید پرداخت';
case 100:
return 'پرداخت تایید شده است لطفا منتظر بمانید';
case 101:
return 'پرداخت قبلاً تایید شده است';
default:
return 'Error handeling';
}
}
unset ($_SESSION['post-data']['name']);
unset ($_SESSION['post-data']['phone']);
if($_GET['order_desc']){
unset ($_SESSION['post-data']['order_desc']);
}
unset ($_SESSION['order_id']);
unset ($_SESSION['shopping_cart']);
session_start();
session_destroy();
session_commit();
just add session_destroy($_SESSION["your_session]); at the end of your code and same for session_commit
I am integrating a Payment Button with Oppwa API,
But with the method that brings me the "CheckoutId".
What happens I have to send all the parameters.
$total = 120;
$iva = 004012000000000012;
$totalTarifa12 = 053012000000000100;
$totalBase0 = 052012000000000200;
$email = "JonathanVeraMarin98#outlook.com";
$primer_nombre = "Jonathan";
$segundo_nombre = "Fernando";
$apellido = "Vera";
$cedula = "0952152525";
$trx = 123456789;
$ip_address = '05100817913101';
$finger = 'https://test.oppwa.com/v1/checkouts';
$merchterm= '1000000505_PD100406';
$telefono ='2172161';
$direccion_cliente = 11222;
$pais_cliente = 121212;
$direccion_entrega = '1600 Pennsylvania Ave NW';
$pais_entrega = 121212;
$checkoutId = prepareCheckout($items,$total,$iva,$totalTarifa12,$totalBase0,$email,$primer_nombre,$segundo_nombre,$apellido,$cedula,$trx,$ip_address,$finger,$merchterm,$telefono,$direccion_cliente,$pais_cliente,$direccion_entrega,$pais_entrega);
These are the values of the burned parameters that I sent to the function
function prepareCheckout($items,$total,$iva,$totalTarifa12,$totalBase0,$email,$primer_nombre
,$segundo_nombre,$apellido,$cedula,$trx,$ip_address,$finger,$merchterm,
$telefono,$direccion_cliente,$pais_cliente,$direccion_entrega,$pais_entrega){
$finger = urlencode($finger);
$i =0;
$url = "https://test.oppwa.com/v1/checkouts";
$iva = str_replace('.', '', $iva);
$totalTarifa12 = str_replace('.', '', $totalTarifa12);
$totalBase0 = str_replace('.', '', $totalBase0);
$valueIva = str_pad($iva,12,'0'.STR_PAD_LEFT);
$valueTotalIva = str_pad($totalTarifa12,12,'0'.STR_PAD_LEFT);
$valueIvaTotalBase0 = str_pad($totalBase0,12,'0'.STR_PAD_LEFT);
$data = "authentication.userId=8a8294184b4f2868014b4f86f767015d" .
"&authentication.password=F8T7N4PD" .
"&authentication.entityId=8a8294184b4f2868014b4f87bf160173" .
"&amount=".$total.
"¤cy=USD".
"&paymentType=DB".
"&customer.givenName=".$primer_nombre.
"&customer.middleName=".$segundo_nombre.
"&customer.surname=".$apellido.
"&customer.ip=".$ip_address.
"&customer.merchantCustomerId=00000000001".
"&merchantTransactionId=transaction_".$trx.
"&customer.email=".$email.
"&customer.identificationDocType=IDCAD".
"&customer.identificationDocId=".$cedula.
"&customer.phone=".$telefono.
"&billing.street1=".$direccion_cliente.
"&billing.country=".$pais_cliente.
"&shipping.street1=".$direccion_entrega.
"&shipping.country=".$pais_entrega.
"&risk.paramters[USER_DATA2]=MiComercio".
"customParamters[".$merchterm."]=00810030070103910004012".$valueIva.
"05100817913101052012".$valueIvaTotalBase0."053012".$valueTotalIva;
foreach ($items["cart"] as $c )
{
$data.="&cart.items[".$i."].name =".$c["product_name"];
$data.="&cart.items[".$i."].description ="."Descripcion: ".$c["product_name"];
$data.="&cart.items[".$i."].price =".$c["product_price"];
$data.="&cart.items[".$i."].quantity= ".$c["q"];
}
$data.= "&testMode=EXTERNAL";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization:Bearer OGE4Mjk0MTg1MzNjZjMxZDAxNTMzZDA2ZmQwNDA3NDh8WHQ3RjIyUUVOWA=='));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// this should be set to true inproduction
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$responseData = curl_exec($ch);
if(curl_errno($ch)) {
return curl_error($ch);
}
curl_close($ch);
return $responseData;
}
My function that generates a checkoutId.
The problem I have is in the foreach I know that it is going through an array but I get an error because I don't know what the condition $ items ['cart'] refers to
foreach ($items["cart"] as $c )
{
$data.="&cart.items[".$i."].name =".$c["product_name"];
$data.="&cart.items[".$i."].description ="."Descripcion: ".$c["product_name"];
$data.="&cart.items[".$i."].price =".$c["product_price"];
$data.="&cart.items[".$i."].quantity= ".$c["q"];
}
I've tried it like this
$items = array();
$items['product_name'] = 'Software';
$items['product_name'] = 'Hola';
$items['product_price'] = '50';
$items['q'] = '1';
I hurt:
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\Datafast\index.php on line 63
`
I have been running unit tests using Selenium Server 2.32 and Firefox 24.4 (on CentOS 5) -- just updated Firefox, and moved to Selenium 2.41, and now Selenium won't open a URL. I assume something has changed in either Firefox or Selenium that I need to adapt to, but can't figure out what.
I created as clean a test program as I could, which follows. It works (opens google.com in a Firefox window) using Selenium 2.32, but not in Selenium 2.41. As best I can tell from looking at the Selenium output it is getting a 404 error, but no idea way.
Any help gratefully appreciated !
Test Case in php:
$seleniumUrl = "http://mydomain.com:4444/wd/hub";
$desired_capabilities = array('browserName' => 'firefox');
$results = mycurl(
$seleniumUrl,
'POST',
'/session',
array('desiredCapabilities' => $desired_capabilities),
array(CURLOPT_FOLLOWLOCATION => true));
$seleniumUrl = $results['info']['url'];
$goToUrl = "http://google.com";
mycurl($seleniumUrl, 'POST', '/url', array('url' => $goToUrl));
Here is the source to mycurl function:
function mycurl(
$seleniumUrl,
$http_method,
$command,
$params = null,
$extra_opts = array()) {
if ($params && is_array($params) && $http_method !== 'POST') {
throw new Exception(sprintf(
'The http method called for %s is %s but it has to be POST' .
' if you want to pass the JSON params %s',
$command,
$http_method,
json_encode($params)));
}
$url = sprintf('%s%s', $seleniumUrl, $command);
if ($params && (is_int($params) || is_string($params))) {
$url .= '/' . $params;
}
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt(
$curl,
CURLOPT_HTTPHEADER,
array(
'Content-Type: application/json;charset=UTF-8',
'Accept: application/json'));
if ($http_method === 'POST') {
curl_setopt($curl, CURLOPT_POST, true);
if ($params && is_array($params)) {
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($params));
}
} else if ($http_method == 'DELETE') {
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
}
foreach ($extra_opts as $option => $value) {
curl_setopt($curl, $option, $value);
}
$raw_results = trim(curl_exec($curl));
$info = curl_getinfo($curl);
if ($error = curl_error($curl)) {
$msg = sprintf(
'Curl error thrown for http %s to %s',
$http_method,
$url);
if ($params && is_array($params)) {
$msg .= sprintf(' with params: %s', json_encode($params));
}
throw new Exception($msg . "\n\n" . $error);
}
curl_close($curl);
$results = json_decode($raw_results, true);
$value = null;
if (is_array($results) && array_key_exists('value', $results)) {
$value = $results['value'];
}
$message = null;
if (is_array($value) && array_key_exists('message', $value)) {
$message = $value['message'];
}
return array('value' => $value, 'info' => $info);
}
Hi I am sending the push notification using below code. I've a problem in this code.
<?php
class GCMPushMessage
{
var $url = 'http://android.googleapis.com/gcm/send';
var $serverApiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";
var $devices = array();
function setDevices($deviceIds)
{
if (is_array($deviceIds)) {
$this->devices = $deviceIds;
} else {
$this->devices = array(
$deviceIds
);
}
}
function send($message)
{
if (!is_array($this->devices) || count($this->devices) == 0) {
$this->error("No devices set");
}
if (strlen($this->serverApiKey) < 8) {
$this->error("Server API Key not set");
}
$fields = array(
'registration_ids' => $this->devices,
'data' => array(
"msg" => $message
)
);
$headers = array(
'Authorization: key=' . $this->serverApiKey,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $this->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));
// Execute post
$result = curl_exec($ch);
$this->StripResponseFromGCM(json_decode($result));
// Close connection
curl_close($ch);
return $result;
}
function error($msg)
{
echo "Android send notification failed with error:";
echo "\t" . $msg;
exit(1);
}
function StripResponseFromGCM($response)
{
//canonicalID's are the
if ($response->failure == 0 && $response->canonical_ids == 0)
return;
for ($i = 0; $i < sizeof($response->results); $i++) {
if (isset($response->results[$i]->registration_id)) { //if new registrationID is sent as canonicalID
//update this registrationID in the database
} else if ($response->results[$i]->error == "Unavailable") {
// user with index == $i is unavailable
} else if ($response->results[$i]->error == "InvalidRegistration") {
// user with index == $i has InvalidRegistration ID
} else if ($response->results[$i]->error == "NotRegistered") {
// user with index == $i is not registered
}
}
}
}
$msg = array(
'data' => array(
'msg' => 'just a simple message'
)
);
require_once('connection.php');
$sql = mysql_query("select gcmid from gcmid");
$new_array = mysql_fetch_array($sql);
print_r($new_array);
$obj = new GCMPushMessage();
$obj->setDevices($new_array);
$obj->send($msg);
?>
If i put a single id in setDevices method then it is working fine but if i
fetching the gcm ids from database and passing it to method setDevices then the code is not working.It suppose to send push notification to devices but it is not working.