convert data to JSON array - php

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.

Related

how to get multiple values from JSON object

i try to get results from my server. my application sending an array with users info and should insert that into the DB.
i get the following result:
{"flag":"failed","msg":"insert event","event id":"89","invitedusers":"[0508690186, 0508690187]","size_invited":1,"user_query":"SELECT id From users WHERE "}
and i would like to know how can i read the values in PHP under "invitedusers":"[0508690186, 0508690187]"
this is my php code:
<?php
/**
* Created by PhpStorm.
* User: matant
* Date: 9/17/2015
* Time: 2:56 PM
*/
include 'response_process.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"];
$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(kind_of_sport,event_date,start_time,end_time,longtitude,latitude,private,gender,min_age,max_participants,scheduled,event_status)
VALUES ('$sport','$date','$s_time','$e_time','$lon','$lat','$event_type','$gen','$min_age','$max_p','$sched','1')") or die (mysqli_error($dblink));
if (!$result) {
$output["flag"] = "failed to create event";
// return (json_encode($output));
}
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);
$output["event id"]=$row["id"];
$json = json_decode($_POST["invitedUsers"]);
$invited_users = str_replace("\\","",$json);
$output["invitedusers"] = $_POST["invitedUsers"] ;
$output["size_invited"] = count($_POST["invitedUsers"]);
$query_users = "SELECT id From users WHERE ";
$i=0;
foreach($invited_users as $user) {
if ($i < (count($invited_users) - 1))
// add a space at end of this string
$query_users .= "users.mobile = '".$user[$i]."' or ";
else {
// and this one too
$query_users .= "users.mobile = '".$user[$i]."' ";
$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";
}*/
}
$output["flag"] = "failed";
}
}
else {
$output["flag"] = "failed";
$output["msg"] = "Place is already occupied in this time";
}
}
return json_encode($output);
}
}
i resolve this issue by passing a JSON object from the application and using
json_decode method which convert it back.

SQL Query in PHP script doesnt fill table in database

In PHP script I parsed some .csv file and trying to execute on a few ways and this is a closest I can get. When I run query manually in database everything is o.k but when I go through the the script I just got New record created successfully and the table stays empty except ID which count how many inserts I got.
o.k that's cool optimization but I still don't getting the data. Yap the $dataPacked is clear below is my whole script can you pls gave some suggestion.
<?php
class AdformAPI {
private $baseUrl = 'https://api.example.com/Services';
private $loginUrl = '/Security/Login';
private $getDataExportUrl = '/DataExport/DataExportResult?DataExportName=ApiTest';
public function login($username, $password) {
$url = $this->baseUrl . $this->loginUrl;
$params = json_encode(array('UserName' => $username, 'Password' => $password));
$response = $this->_makePOSTRequest($url, $params);
$response = json_decode($response, true);
if (empty($response['Ticket'])) {
throw new \Exception('Invalid response');
}
// var_dump($response);
return $response['Ticket'];
}
public function getExportData($ticket) {
$url = $this->baseUrl . $this->getDataExportUrl;
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Ticket: '. $ticket
));
$output = curl_exec($ch);
return $output;
}
public function downloadFileFromUrl($url, $savePath) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSLVERSION,3);
$data = curl_exec ($ch);
$error = curl_error($ch);
curl_close ($ch);
// if (!is_dir($savePath) && is_writable($savePath)) {
$file = fopen($savePath, "w+");
fputs($file, $data);
fclose($file);
// } else {
// throw new \Exception('Unable to save file');
// }
}
private function _makePOSTRequest($url, $json_data) {
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, count($json_data));
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
}
// Login and data download url
$api = new AdformAPI();
$ticket = $api->login('example', '123546');
$exportDataResponseJson = $api->getExportData($ticket);
$exportDataResponse = json_decode($exportDataResponseJson, true);
if (empty($exportDataResponse['DataExportResult']) || $exportDataResponse['DataExportResult']['DataExportStatus'] != "Done") {
throw new \Exception('GetDataExport invalid response');
}
// Download zip
$fileDir = '/var/www/html/app-catalogue/web/export';
$fileName = 'report.zip';
$filePath = $fileDir . DIRECTORY_SEPARATOR . $fileName;
$api->downloadFileFromUrl($exportDataResponse['DataExportResult']['DataExportResultUrl'], $filePath);
// Unzip
$zip = new ZipArchive;
$res = $zip->open($filePath);
$csvFilename = '';
if ($res === true) {
for ($i = 0; $i < $zip->numFiles; $i++) {
$csvFilename = $zip->getNameIndex($i);
}
$zip->extractTo($fileDir);
$zip->close();
} else {
throw new Exception("Unable to unzip file");
}
// Parse CSV
$csvPath = $fileDir . DIRECTORY_SEPARATOR . $csvFilename;
if (is_readable($csvPath)) {
$dataCsv = file_get_contents($fileDir . DIRECTORY_SEPARATOR . $csvFilename);
$dataArr = explode("\n", $dataCsv);
$dataPacked = array();
foreach ($dataArr as $row) {
$row = str_replace(" ", "", $row);
//$row = wordwrap($row, 20, "\n", true);
$row = preg_replace('/^.{20,}?\b/s', "$0&nbsp", $row);
$row = explode("\t", $row);
$dataPacked[] = $row;
}
}
// SQL Connestion
$servername = "192.168.240.22";
$username = "liferaypublic";
$password = "liferaypublic";
$dbname = "liferay_dev";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->query("set names 'utf8'");
$sql = " INSERT INTO ho_adform_reports (`Timestamp`, `Campaign`, `Paid_Keywords`, `Natural_Search_Keywords`, `Referrer_Type`, `Referrer`, `Page`, `Order_ID`)
VALUES ";
$flag = true;
foreach($dataPacked as $rowArray) {
if($flag or count($rowArray)<= 7) { $flag = false; continue; }
$sql .= "('".implode("','", $rowArray)."'),";
}
$sql = trim($sql,",");
echo $sql; //For debug only
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
//var_dump($dataPacked);
try this - I am assuming you have sanitised the values in $dataPacked.
Note edited to addslashes just in case.
$conn->query("set names 'utf8'");
$sql = " INSERT INTO ho_adform_reports (`Timestamp`, `Campaign`, `Paid_Keywords`, `Natural_Search_Keywords`, `Referrer_Type`, `Referrer`, `Page`, `Order_ID`)
VALUES ";
$flag = true;
foreach($dataPacked as $rowArray) {
if($flag or count($rowArray)<= 7) { $flag = false; continue;}
foreach ($rowArray as $k=>$v) {
$sanitised = preg_replace("/[^[:alnum:][:space:]]/ui", '', $v);
$rowArray[$k] = addslashes(trim($sanitised));
}
$sql .= "('".implode("','", $rowArray)."'),";
}
$sql = trim($sql,",");
echo $sql; //For debug only
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();

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;
}
}
?>

GCM send message to all devices [closed]

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;
}
?>

PHP CURL request not working , not getting any data back [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What’s wrong with my PHP curl request, please help .. I’m not getting any data back
I'm posting XML data to a URL that is supposed to send me (echo) back results, and instead of sending them back to me , this is what I get after running the PHP .. My curl code is below this result ... I am suspecting that something might be wrong with my CURL code below, how can I actually get the results back from the XML data posted to the URL(mysgproc.php), I posted the url code as well ? Thanks a bunch
HTTP/1.1 200 OK
Date: Fri, 19 Oct 2012 16:30:26 GMT
Server: Apache/2.2.9 (Fedora)
Set-Cookie: ZDEDebuggerPresent=php,phtml,php3; path=/
Content-Length: 238
Connection: close
Content-Type: text/html
<?xml version="1.0" encoding="UTF-8"?><iniResponseMsg deliveryTimeStamp="19/10/2012 16:30:26 GMT" messageID="9d085e45-9e9b-11da-befd-0014221b359d" correlationID="69c8277d-77af-4fd9-8cc0-7c30d2963bee"> <state>fail</state></iniResponseMsg>
Below is my code ...
<?php
$url ="http://127.0.0.1/sens/msgproc.php";
$xml_data = file_get_contents("/usr/local/www/data/message_test.xml");
#$header ="POST HTTP/1.0 \r\n";
#$header .="Content-type: text/xml \r\n";
#$header .="Content-length: ".strlen($xml_data)." \r\n";
#$header .="Content-transfer-encoding: text\r\n";
#$header .="Connection: close \r\n\r\n";
#$header .= $xml_data;
$headers = array('Content-Type: text/xml','Content-Transfer-Encoding: text','Connection: close');
$ch = curl_init();
curl_setopt ($ch,CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_POSTFIELDS,$xml_data);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch, CURLOPT_TIMEOUT, 4);
#curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $header);
$data = curl_exec($ch); // if the post is successful , the server will return some data.
#$info = curl_getinfo($ch);
#
#if(!curl_errno($ch))
# echo 'It took '.$info['total_time'].'seconds to send a request to'.$info['url'];
#
# else
#
curl_close($ch);
echo $data;
?>
Here is the msgproc.php code
<?php
//$pass='go';
/*******************************************************************************
* COMPONENT NAME:
* msgproc.php
*
* DESCRIPTION:
* This script accepts the various XML documents from G*.
* The document is passed to the correct routine
* in msgproc.php based on what it is.
*
*******************************************************************************/
require('sensdb.php');
require('dbutil.php');
require('msgproc_util.php');
// first this is to pipe all output to the buffer for loggin later in the file
// echo and print statements will get logged instead of outputted
ob_start();
//$raw_post_data = $HTTP_RAW_POST_DATA;
$raw_post_data = file_get_contents("php://input");
$time_log = date("d/m/Y G:i:s") . ' - aeroastro sensor sys time';
/* CONNECT TO THE DATABASE */
sensdb_connect();
$script_time = date("M-d-Y H:i:s");
// logging variables
$type='';
$byte_count=0;
$message_id='';
$error='';
$error_type='';
$source = $_SERVER['REMOTE_ADDR'];
/*******************************************************************************
* COMPONENT NAME:
* main process
*
* DESCRIPTION:
*
*******************************************************************************/
/****** formerly function test_read_xml_post() ***********************/
//$fp = fopen("/usr/local/www/data/sensor/sens/message_test.xml", "r");
//$fp = fopen("php://input", "r");
echo "string length:" . strlen($raw_post_data) . ' ';
// reject all data not from Globalstar of development
//if ( $source == "207.88.248.142" ) {
$data = trim($raw_post_data);
//} else {
// $data = NULL;
//}
$byte_count += strlen($data);
//fclose($fp);
// test of php5 parsing xml .... much easier
if ( $xml = simplexml_load_string($data) ) {
// innocent until proven guilty
$status = true;
// this will help us find the root element to determine message type
$dom = dom_import_simplexml($xml);
$xml_root = $dom->tagName;
// process stumessages here
if ( $xml_root == 'stuMessages' ) {
$type = 'STxMessage';
// what is the message id
$xml_messageID = $xml->xpath('/stuMessages/#messageID');
foreach ( $xml_messageID as $id ) {
$message_id = $id;
}
// what is the packet time
$packetTimes = $xml->xpath('/stuMessages/#timeStamp');
foreach ( $packetTimes as $_time ) {
$packetTime = $_time;
}
$time_log .= "\n". $packetTime . ' - globalstar packet time';
// how many messages
$message_count = count($xml->xpath('/stuMessages/stuMessage'));
if ( $message_count >= 1 ) {
// fomat the sql string
$sql = get_msglog_sql($type, $source, $byte_count, $message_id, $error );
if ( mysql_query($sql) ) {
// get the insert id
// be careful not to change the sql above which might break our ability here to get the last insert id
$incoming_id = mysql_insert_id();
echo $script_time . " - stu_message packet $message_id logged: insert_id:$incoming_id";
} else {
echo $script_time . " - stu_message failed logging";
}
// mysql_query("LOCK TABLES STxMessage WRITE");
// mysql_query("SET AUTOCOMMIT = 0");
mysql_query("BEGIN");
foreach( $xml->stuMessage as $stuMessage ) {
$unixtime = $stuMessage->unixTime;
$gps = $stuMessage->gps;
$payload = $stuMessage->payload;
// convert to an ESN int
$esn = $stuMessage->esn;
$esn = esn_to_num($esn);
// test the message time against system time
// JL 2007
$time_log .= "\n" . gmdate("d/m/Y H:i:s", "$unixtime") . " - packet stu message time";
// JL 2006 Apr
// log message data larger than 255 chars for TSM account a la Tony B
// these messages don't fit in our DB
if ( strlen($payload) > 255 ) {
// log any output
$large_message_log = '/usr/local/www/logs/large_message_log';
$sql = 'INSERT INTO STxLargeMessage ( ESN,GPS,Payload,UnixTime,IncomingID) values ("'.$esn.'","'.$gps.'","'.$payload.'","'.$unixtime.'","'.$incoming_id.'")';
// Perform Insert of large message
$result = #mysql_query($sql);
// Let's make sure the file exists and is writable first.
if ( is_writable($large_message_log) ) {
// The file pointer is at the bottom of the file hence
$handle = #fopen($large_message_log, 'a');
// Write $response to our opened file.
#fwrite($handle, "\n".$data);
#fclose($handle);
}
}
// do we have an ESN for this message
// $select_esn = 'select ESN from STx where ESN = "'.$esn.'"';
// $result = mysql_query($select_esn);
// $result_count = mysql_num_rows($result);
$sql = 'INSERT INTO STxMessage( ESN,GPS,Payload,UnixTime,IncomingID) values ("'.$esn.'","'.$gps.'","'.$payload.'","'.$unixtime.'","'.$incoming_id.'")';
// Perform Insert
$result = mysql_query($sql);
$GMT_unixtime = gmdate("Y-m-d H:i:s", "$unixtime");
$update = 'update STx set MessageCount = MessageCount + 1, LastMessageTime = "' . $GMT_unixtime . '" where ESN = "' . $esn . '"';
// increment the message count by 1
mysql_query($update);
unset($update);
// Check db result
if ( !$result ) {
$status = false;
// log the error
echo 'Invalid query: ' . mysql_error() . "\n";
echo $message .= 'Whole query: ' . $query;
}
unset($result);
unset($unixtime);
unset($gps);
unset($payload);
unset($esn);
}
if ( $status ) {
mysql_query("COMMIT");
} else {
mysql_query("ROLLBACK");
}
// mysql_query("UNLOCK TABLES");
// mysql_query("SET AUTOCOMMIT = 1");
} else { // no data but valid xml, return pass, probably G* "pining" aeroastro for life
$error = "no data in xml packet id:" . $message_id . "\n";
echo $error;
}
// make our response xml for globalstar
$response = make_globalstar_response_xml('stuResponseMsg', $message_id, $status);
} elseif ( $xml_root == 'prvmsgs' ) { // process prvmsgs messages
/*******************************************************************************
* COMPONENT NAME:
* PRVMSGS
*
* DESCRIPTION:
* These routines accept the PRVMSGS sent by Globalstar in response to the
* INIMSGS that were sent. This routine stores the PRVMSGS into the database,
* and also sends a respose message back to Globalstar.
*
*******************************************************************************/
$type = 'PrvMessage';
// what is the message id
$xml_messageID = $xml->xpath('/prvmsgs/#prvMessageID');
foreach ( $xml_messageID as $id ) {
$message_id = $id;
}
// how many messages
$message_count = count($xml->xpath('/prvmsgs/prvmsg'));
if ( $message_count >= 1 ) {
// fomat the sql string for logging
$sql = get_msglog_sql($type, $source, $byte_count, $message_id, $error );
if ( mysql_query($sql) ) {
// get the insert id
$incoming_id = mysql_insert_id();
echo $script_time . " - PrvMessage packet $message_id logged";
} else {
echo $script_time . " - PrvMessage failed logging";
}
mysql_query("BEGIN");
// loop through the messages
foreach( $xml->prvmsg as $prvmsg ) {
$esn = esn_to_num($prvmsg->esn);
$provid = $prvmsg->provID;
$tstart = $prvmsg->tStart;
$tend = $prvmsg->tEnd;
$txretryminsec = $prvmsg->txRetryMinSec;
$txretrymaxsec = $prvmsg->txRetryMaxSec;
$txretries = $prvmsg->txRetries;
$rfchannel = $prvmsg->rfChannel;
$sql = 'REPLACE INTO PrvMessage ( ESN, ProvID, TStart, TEnd, TxRetryMinSec, TxRetryMaxSec, TxRetries, RFChannel, IncomingID) values ("'.$esn.'","'.$provid.'","'.$tstart.'","'.$tend.'","'.$txretryminsec.'","'.$txretrymaxsec.'","'.$txretries.'","'.$rfchannel.'","'.$incoming_id.'")';
// Perform Insert
$result = mysql_query($sql);
// insert status "change" record
$insert_sql = 'insert INTO STxStatusChangeHistory (StatusChangeID, ESN, Status, StatusChangeTimestamp) values ("","'.$esn.'","Provisioned",NOW())';
// Perform Insert
$insert = mysql_query($insert_sql);
// Check result
if (! $result) {
$status = false;
// log the error
echo 'Invalid provisioning: ' . mysql_error() . "\n";
echo 'Whole query: ' . $sql;
} else {
$sql = 'UPDATE STx SET Status="Provisioned" WHERE ESN ="'.$esn.'"';
$result = mysql_query($sql);
// Check result
if (! $result) {
$status = false;
// log the error
echo 'Invalid STx update during provisioning: ' . mysql_error() . "\n";
echo 'Whole query: ' . $sql;
}
}
unset($result);
unset($esn);
unset($provid);
unset($tstart);
unset($tend);
unset($txretryminsec);
unset($txretrymaxsec);
unset($txretries);
unset($rfchannel);
}
if ( $status ) {
mysql_query("COMMIT");
} else {
mysql_query("ROLLBACK");
msglog_update($message_id, "PrvMessage INSERT ERROR");
}
}
// make our response xml for globalstar
$response = make_globalstar_response_xml('prvResponseMsg', $message_id, $status);
} elseif ( $xml_root == 'instmsgs' ) { // process instmsgs messages
/*******************************************************************************
* COMPONENT NAME:
* INSTMSGS
*
* DESCRIPTION:
* After the VAR gets the PRVMSGS and installs the RTU, it will send the
* INSTMSG back here to indicate where the unit was installed.
*
*******************************************************************************/
$type = 'InstMessage';
// what is the message id
$xml_messageID = $xml->xpath('/instmsgs/#instMessageID');
foreach ( $xml_messageID as $id ) {
$message_id = $id;
}
// how many messages
$message_count = count($xml->xpath('/instmsgs/instmsg'));
if ( $message_count >= 1 ) {
// fomat the sql string for logging
$sql = get_msglog_sql($type, $source, $byte_count, $message_id, $error );
if ( mysql_query($sql) ) {
// get the insert id
$incoming_id = mysql_insert_id();
echo $script_time . " - InstMessage packet $message_id logged";
} else {
echo $script_time . " - InstMessage failed logging";
}
mysql_query("BEGIN");
// loop through the messages
foreach( $xml->instmsg as $instmsg ) {
$esn = esn_to_num($instmsg->esn);
$provid = $instmsg->provID;
$rfchannel = $instmsg->rfChannel;
$tactual = $instmsg->tActual;
$deltat = $instmsg->deltaT;
$latitude = $instmsg->latitude;
$longitude = $instmsg->longitude;
$txretries = $instmsg->txRetries;
$txoffset = $instmsg->txOffset;
$txretryminsec = $instmsg->txRetryMinSec;
$txretrymaxsec = $instmsg->txRetryMaxSec;
$powerlevel = $instmsg->powerLevel;
$sql = 'REPLACE INTO InstMessage ( ESN
,ProvID
,IncomingID
,RFChannel
,TActual
,DeltaT
,Latitude
,Longitude
,TxRetries
,TxOffset
,TxRetryMinSec
,TxRetryMaxSec
,PowerLevel ) values ("'.$esn.'"
,"'.$provid.'"
,"'.$incoming_id.'"
,"'.$rfchannel.'"
,"'.$tactual.'"
,"'.$deltat.'"
,"'.$latitude.'"
,"'.$longitude.'"
,"'.$txretries.'"
,"'.$txoffset.'"
,"'.$txretryminsec.'"
,"'.$txretrymaxsec.'"
,"'.$powerlevel.'")';
// Perform Insert
$result = mysql_query($sql);
// Check result
if (! $result) {
$status = false;
// log the error
echo 'Invalid InstMessage sql: ' . mysql_error() . "\n";
echo 'Whole query: ' . $sql;
} else {
$sql = 'UPDATE STx SET Status="Installed" WHERE ESN ="'.$esn.'"';
$result = mysql_query($sql);
// Check result
if (! $result) {
$status = false;
// log the error
echo 'Invalid STx update during Install: ' . mysql_error() . "\n";
echo 'Whole query: ' . $sql;
}
}
unset($result);
unset($esn);
unset($provid);
unset($tstart);
unset($tend);
unset($txretryminsec);
unset($txretrymaxsec);
unset($txretries);
unset($rfchannel);
unset($txoffset);
unset($txretryminsec);
unset($txretrymaxsec);
unset($powerlevel);
}
if ( $status ) {
mysql_query("COMMIT");
} else {
mysql_query("ROLLBACK");
msglog_update($message_id, "InstMessage INSERT ERROR");
}
}
// make our response xml for globalstar
$response = make_globalstar_response_xml('instResponseMsg', $message_id, $status);
} elseif ( $xml_root == 'inimsgs' ) { // process inimsgs messages
/*******************************************************************************
* COMPONENT NAME:
* INIMSGS
*
* DESCRIPTION:
* The 'INIMSGS' are the messages sent to begin the provisioning process. The
* message contains a range of ESN numbers to be provisiond. The 'INIMSGS'
* are forwarded to Globalstar. Then, the 'get_prvmsgs' function is called
* to poll the database for the response 'prvmsgs' that Globalstar will send.
*
*******************************************************************************/
$type = 'inimsgs';
// what is the message id
$xml_messageID = $xml->xpath('/inimsgs/#iniMessageID');
foreach ( $xml_messageID as $id ) {
$message_id = $id;
}
// how many messages
$message_count = count($xml->xpath('/inimsgs/inimsg'));
if ( $message_count >= 1 ) {
/* DONT FORGET - have a trigger in the database to set a default route for NASCORP */
$sql = "INSERT INTO STx (ESN, RouteID, GroupID, SubGroupID, STxModel, STxModelGenType, STxName, Note, Status, FilterProfile) VALUES ";
$sep = "";
/* FOR EACH OF THE MESSAGES IN THE PACKET.. .*/
foreach ( $xml->inimsg as $inimsg ) {
$groupid = $inimsg->groupID;
$subgroupid = strlen($inimsg->subGroupID) ? $inimsg->subGroupID : 'NULL';
/* FIRST CHECK THAT THE REQUESTED RANGE IS AVAILABLE */
$esnStart = $inimsg->esnStart;
$esnEnd = $inimsg->esnEnd;
$number = check_esn_range($esnStart, $esnEnd, $inuse);
$isreal = ($inimsg->isReal == 'Yes') ? true : false;
$route_id = get_route_id($groupid, $inimsg->routeAddress);
if ( $number > 0 ) {
/* SPLIT THE ESN NUMBER INTO MANUFACTURER AND SERIAL NUMBER */
$esnS = explode('-', $esnStart);
$esnE = explode('-', $esnEnd);
/* FOR EACH ESN IN THE SPECIFIED RANGE... */
for ( $mfg=(int) $esnS[0]; $mfg <= (int) $esnE[0]; $mfg++ ) {
for ( $ser=(int) $esnS[1]; $ser <= (int) $esnE[1]; $ser++ ) {
$sxtmodel = $inimsg->stxModel;
$sxtmodelgentype='1';
switch ($sxtmodel) {
case "101-1":
$sxtmodel = '101';
$sxtmodelgentype = "1";
break;
case "101-2":
$sxtmodel = '101';
$sxtmodelgentype = "2";
break;
case "101-3":
$sxtmodel = '101';
$sxtmodelgentype = "3";
break;
}
$esn = (($mfg << 23) | $ser);
$sql .= $sep;
$sql .= sprintf("(%d ,%d ,%d ,%s ,'%s' ,'%s' ,'%s' ,'%s' ,'%s' ,'%s' )",
$esn
,$route_id
,$groupid
,$subgroupid
,mysql_escape_string($sxtmodel)
,$sxtmodelgentype
,mysql_escape_string($inimsg->stxName)
,mysql_escape_string($inimsg->note)
,$isreal ? 'Initiated' : 'Fake'
,$inimsg->filterProfile);
$sep = ",";
}
}
$groupid = $inimsg->groupID;
$subgroupid = $inimsg->subGroupID;
$esnstart = esn_to_num($inimsg->esnStart);
$esnend = esn_to_num($inimsg->esnEnd);
$stxmodel = $inimsg->stxModel;
$stxname = $inimsg->stxName;
// new filter setting
$filterprofile = $inimsg->filterProfile;
$routeaddress = $inimsg->routeAddress;
// $mobility = $inimsg->mobility;
// $latdefault = $inimsg->latDefault;
// $londefault = $inimsg->lonDefault;
$stxspacing = $inimsg->txSpacing;
// $txfrequency = $inimsg->txFrequency;
// $trequestedstart = $inimsg->tRequestedStart;
// $trequestedend = $inimsg->tRequestedEnd;
$note = $inimsg->note;
$isreal = $inimsg->isReal;
$insert_inimessage = 'INSERT INTO IniMessage (GroupID
,SubGroupID
,ESNStart
,ESNEnd
,STxModel
,STxName
,FilterProfile
,TxSpacing
,RouteAddress
,Note
,IsReal) VALUES ("'.$groupid.'"
,"'.$subgroupid.'"
,"'.$esnstart.'"
,"'.$esnend.'"
,"'.$stxmodel.'"
,"'.$stxname.'"
,"'.$filterprofile.'"
,"'.$stxspacing.'"
,"'.$routeaddress.'"
,"'.$note.'"
,"'.$isreal.'")';
mysql_query("BEGIN");
if ( mysql_query($insert_inimessage) ) {
// not used for anything
$inserted = true;
} else {
$status=false;
}
unset($groupid);
unset($subgroupid);
unset($esnstart);
unset($esnend);
unset($stxmodel);
unset($stxname);
unset($filterprofile);
unset($routeaddress);
unset($mobility);
unset($stxspacing);
unset($note);
unset($isreal);
} else {
$status = false;
echo $script_time . " invalid ESN range\n".$raw_post_data;
}
}
/* IF THE CONTENTS OF THE MESSAGE LOOKED OK, THEN COMMIT
IT TO THE DATABASE... */
/* CREATE THE STx TABLE ENTRIES */
if ( $status ) {
if ( $status = mysql_query($sql) ) {
mysql_query("COMMIT");
} else {
$doc->errors = mysql_error();
mysql_query("ROLLBACK");
}
} else {
$doc->errors = mysql_error();
mysql_query("ROLLBACK");
}
} else {
$status = false;
echo $script_time . " no messages in xml \n".$raw_post_data;
}
// make our response xml for globalstar
$response = make_globalstar_response_xml('iniResponseMsg', $message_id, $status);
}
} else {
// failed to load xml so lets fail
$status=false;
$response = make_globalstar_response_xml('xml_error', 0, $status);
echo $script_time . " - xml error\n" . $raw_post_data;
}
// log any output
$msgproc_log = '/usr/local/www/logs/msgproc_log';
// collect any trash here for logging
$buffer_string = ob_get_contents()."\n";
// Let's make sure the file exists and is writable first.
if ( is_writable($msgproc_log) ) {
// The file pointer is at the bottom of the file hence
$handle = #fopen($msgproc_log, 'a');
// Write $response to our opened file.
#fwrite($handle, $buffer_string);
#fclose($handle);
}
//empty buffer to logs so that globalstar gets response only
ob_end_clean();
mysql_close();
// send the output for Globalstar to see
echo $response;
?>
msgproc.php has dependencies. No one has the time to debug it. So do this:
Try tracing into the server processing code.
echo __LINE__, PHP_EOL; flush(); // every few lines :)
// even followed by a die; to slowly move deeper into the code
Poor man's debugging. And see where output stops, slowly pinpoint the issue. Also set_error_handler and set_exception_handler and see if anything gets caught.

Categories