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

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.

Related

SELECT statement can't find records that were just inserted in the same http request

I've got a simple class with two methods: add and process.
require_once('MailQueue.config.php');
require_once('class.phpmailer.subclass.php');
class MailQueue {
private $dbServer;
private $dbName;
private $dbUsername;
private $dbPassword;
private $mailLimit;
private $mailLimitTimeUnit;
private $db;
function __construct() {
global $CONFIG;
// Set database connection variables
$this->dbServer = $CONFIG['dbServer'];
$this->dbName = $CONFIG['dbName'];
$this->dbUsername = $CONFIG['dbUsername'];
$this->dbPassword = $CONFIG['dbPassword'];
// Set app settings
$this->mailLimit = $CONFIG['mailLimit'];
$this->mailLimitTimeUnit = $CONFIG['mailLimitTimeUnit'];
// Connect to database
$this->db = new mysqli($this->dbServer, $this->dbUsername, $this->dbPassword, $this->dbName);
if($this->db->connect_error) {
die("Error connecting to MailQueue.<br />".$this->db->connect_error);
}
}
function add($data) {
$sqls = "";
foreach($data as $d) {
$sqls .= "INSERT INTO mailqueue (".
"desiredSendTime, ".
"fromName, ".
"fromAddress, ".
"toName, ".
"toAddress, ".
"subject, ".
"bodyHtml ".
") VALUES (".
"'".$d['sendAt']."',".
"'".$d['fromName']."',".
"'".$d['fromAddress']."',".
"'".$d['toName']."',".
"'".$d['toAddress']."',".
"'".$d['subject']."',".
"'".$d['body']."'".
");";
}
$insertIds = Array();
if(!$this->db->multi_query($sqls)){
die("Error adding emails to mailqueue: (".$this->db->errno.") ".$this->db->error);
}
// fetch insert ids
do {
$insertIds[] = $this->db->insert_id;
} while($this->db->more_results() && $this->db->next_result());
return $insertIds;
}
function processQueue($numberOfMessages, $preferredEmailIds="") {
// Get number of emails already sent in this timeframe
// Do not check for the last timeUnit, but for the timeUnit we're currently in, e.g.
// if timeUnit = 'hour', count the processed emails in de current hour, not in the last 60 minutes.
switch($this->mailLimitTimeUnit) {
case 'year':
$startOfCurrentTimeframe = date('Y-01-01 00:00:00');
break;
case 'month':
$startOfCurrentTimeframe = date('Y-m-01 00:00:00');
break;
case 'day':
$startOfCurrentTimeframe = date('Y-m-d 00:00:00');
break;
case 'hour':
$startOfCurrentTimeframe = date('Y-m-d H:00:00');
break;
case 'minute':
$startOfCurrentTimeframe = date('Y-m-d H:i:00');
break;
default:
$startOfCurrentTimeframe = '';
}
if($startOfCurrentTimeframe != '') {
$successCounter = 0;
$sql = "SELECT ".
"COUNT(*) AS currentCount ".
"FROM ".
"mailqueue ".
"WHERE ".
"actualSendTime BETWEEN '".$startOfCurrentTimeframe."' AND NOW()";
if(!($stmt = $this->db->prepare($sql))) {
die("Prepare failed: (".$this->db->errno.") ".$this->db->error);
}
if(!($stmt->execute())) {
die("Execute failed: (".$stmt->errno.") ".$stmt->error);
}
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$currentCount = $row['currentCount'];
$spaceLeft = $this->mailLimit - $currentCount;
// Don't exceed the mail limits!
if($spaceLeft < $numberOfMessages){
$numberOfMessages = $spaceLeft;
}
// In case of preferred emails, add an explicit filter to accomplish this
if($preferredEmailIds!=""){
$preferredEmailsOnly = "AND id IN (".implode(',', $preferredEmailIds).") ";
} else {
$preferredEmailsOnly = "";
}
// Process new emails
$sql = "SELECT ".
"* ".
"FROM ".
"mailqueue ".
"WHERE ".
"desiredSendTime < NOW() ".
"AND actualSendTime IS NULL ".
$preferredEmailsOnly.
"ORDER BY ".
"desiredSendTime, ".
"id ".
"LIMIT ?";
if(!($stmt = $this->db->prepare($sql))) {
die("Prepare failed: (".$this->db->errno.") ".$this->db->error);
}
if (!$stmt->bind_param("i", $numberOfMessages)){
die("Binding parameters failed: (".$stmt->errno.") ".$stmt->error);
}
if (!$stmt->execute()) {
die("Execute failed: (".$stmt->errno.") ".$stmt->error);
}
$result = $stmt->get_result();
if($result->num_rows > 0) {
$successCounter = 0;
$sqls = "";
while($row = $result->fetch_assoc()) {
$msg = new themedMailer();
$msg->From = $row['fromAddress'];
$msg->FromName = $row['fromName'];
$msg->Subject = $row['subject'];
$msg->Body = $row['bodyHtml'];
$msg->IsMail();
$msg->AddAddress($row['toAddress'], $row['toName']);
if($msg->Send()) {
$successCounter++;
// Save the time of sending to the email in the database
$sqls .= "UPDATE mailqueue SET actualSendTime = NOW() WHERE id = ".$row['id'].";";
} else {
die("Sending mail failed: ".$this->ErrorInfo);
}
}
// Update the sent emails
if(!$this->db->multi_query($sqls)){
die("Failed updating records for sent emails; these emails will be sent again because of this error.");
}
}
$stmt->close();
}
return $successCounter;
}
}
If I use separate http requests to call the add and process functions, it works alright. The add function adds some records in a table and the process function processes some records from the same table (not necessarily the same records).
If I try to combine the two to make process process the records that are inserted by add, the process function simply doesn't find the records that were inserted by the add function. Some code to explain what I've been trying:
This code works fine:
HTTP Request 1:
ERROR_REPORTING(E_ALL);
require_once('../MailQueue.class.php');
$queue = new MailQueue();
$currentTime = date('YmdHis');
$data = Array();
$num = 2000;
for($i=1; $i<=$num; $i++) {
$data[$i] = Array();
$data[$i]['sendAt'] = date('Y-m-d H:i:s');
$data[$i]['fromName'] = 'John Doe';
$data[$i]['fromAddress'] = 'john#doe.com';
$data[$i]['toName'] = 'Jane Doe';
$data[$i]['toAddress'] = 'jane#doe.com';
$data[$i]['subject'] = 'Test message MailQueue '.$currentTime;
$data[$i]['body'] = 'Test message MailQueue '.$currentTime;
}
$queue->add($data);
echo "Added ".$num." new emails to be sent";
HTTP Request 2:
ERROR_REPORTING(E_ALL);
require_once('../MailQueue.class.php');
$try = 50;
$queue = new MailQueue();
echo "Trying to send ".$try." emails.<br />";
$counter = $queue->processQueue($try);
echo "Sent ".$counter." emails.";
if($counter < $try) {
echo " Not all desired emails were sent, so the mail limit was probably reached. Please try again later.";
}
The following code doesn't work, because the SELECT query in the process function returns no records:
Only 1 HTTP Request:
ERROR_REPORTING(E_ALL);
require_once('../MailQueue.class.php');
$queue = new MailQueue();
$currentTime = date('YmdHis');
$try = 50;
$data = Array();
for($i=1; $i<=3; $i++) {
$data[$i] = Array();
$data[$i]['sendAt'] = date('Y-m-d H:i:s');
$data[$i]['fromName'] = 'John Doe '.$i;
$data[$i]['fromAddress'] = 'john#doe.com';
$data[$i]['toName'] = 'Jane Doe';
$data[$i]['toAddress'] = 'jane#doe.com';
$data[$i]['subject'] = 'Test message MailQueue '.$currentTime;
$data[$i]['body'] = 'Test message MailQueue '.$currentTime;
}
// Directly process the added messages
echo "Trying to send ".$try." emails.<br />";
$counter = $queue->processQueue($try, $queue->add($data));
echo "Added 3 new emails to be sent. ".$counter." emails were actually sent.";
Can anyone explain why combining the two functions doesn't work? Autocommit is 1 and I've trying to commit explicitly, but to no avail.

SSE: unexpected MIME type error

I am using a PHP file as a worker for a SSE connection. This is my PHP file:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$mysqli = new mysqli(* data *);
$listings = $mysqli->query("SELECT listing_id, price, buyer_id FROM listings WHERE schedule_requested = '1' AND finished = '0'");
$to_check = array();
while ($li = $listings->fetch_array()) {
$to_check[] = array($li["listing_id"], $li["price"], $li["buyer_id"]);
}
while (true) {
$change = 0;
$listings_2 = $mysqli->query("SELECT listing_id, price, buyer_id FROM listings WHERE schedule_requested = '1' AND finished = '0'");
$different = array();
while ($li_2 = $listings_2->fetch_array()) {
foreach ($to_check as &$li_check) {
if ($li_check[0] === $li_2["listing_id"]) {
if (intval($li_2["price"]) !== intval($li_check[1])) {
$li_check = array($li_2["listing_id"], $li_2["price"], $li_2["buyer_id"]);
$different[] = $li_check;
$change = 1;
}
break;
}
}
}
if ($change === 1) {
echo "data: " . json_encode($different) . PHP_EOL;
echo PHP_EOL;
flush();
}
sleep(1);
}
?>
Even though there is the header that specifies the content-type, I receive an error when I try to use the file:
EventSource's response has a MIME type ("text/html") that is not "text/event-stream". Aborting the connection.
I don't receive that error, anyway, when I am using the following code for the same file (commenting the infinite while loop).
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$mysqli = new mysqli(* data *);
$listings = $mysqli->query("SELECT listing_id, price, buyer_id FROM listings WHERE schedule_requested = '1' AND finished = '0'");
$to_check = array();
while ($li = $listings->fetch_array()) {
$to_check[] = array($li["listing_id"], $li["price"], $li["buyer_id"]);
}
/*while (true) {
$change = 0;
$listings_2 = $mysqli->query("SELECT listing_id, price, buyer_id FROM listings WHERE schedule_requested = '1' AND finished = '0'");
$different = array();
while ($li_2 = $listings_2->fetch_array()) {
foreach ($to_check as &$li_check) {
if ($li_check[0] === $li_2["listing_id"]) {
if (intval($li_2["price"]) !== intval($li_check[1])) {
$li_check = array($li_2["listing_id"], $li_2["price"], $li_2["buyer_id"]);
$different[] = $li_check;
$change = 1;
}
break;
}
}
}
if ($change === 1) {
echo "data: " . json_encode($different) . PHP_EOL;
echo PHP_EOL;
flush();
}
sleep(1);
}*/
echo "data: " . json_encode($different) . PHP_EOL;
echo PHP_EOL;
flush();
?>
I can't understand why it happens.
The SSE standard clearly states that if the response does not contain text/event-stream, it MUST error the connection.
HTTP 200 OK responses that have a Content-Type other than text/event-stream (or some other supported type) must cause the user agent to fail the connection.
SSE protocol

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.

$_GET and isset() url response Json

I have use a lot of answers here to solve almost everything, but i can't figure out how to accomplish this;
I use PHP to get data from my MySQL, and encode to json with url request, so wen I go to miweb. com /_js/ajax/load_content.php?f=1
I get a perfect response from my databesa and echo to json encode, 1 means user with id number 1
my response looks like this:
[{"i":"1","n":"Azul","p":"_imgs\/site\/iconos\/0-100\/22\/activo\/ico_00022_138.jpg"}]
and if i go to miweb. com/_js/ajax/load_content.php?f=2 i will get
[{"i":"2","n":"Lety","p":"_imgs\/site\/iconos\/0-100\/87\/activo\/ico_00087_138.jpg"}]
what i need to accomplish is to go to ?f=1,2
miweb.com /_js/ajax/load_content.php?f=1,2 and get the response in same json like this
[{"i":"1","n":"Azul","p":"_imgs\/site\/iconos\/0-100\/22\/activo\/ico_00022_138.jpg"},
{"i":"2","n":"Lety","p":"_imgs\/site\/iconos\/0-100\/87\/activo\/ico_00087_138.jpg"}]
this is my php scrip:
require '../../system/config.php';
if( isset($_GET['h']) ) {
get_ficha($_GET['h']);
} else {
die("Solicitud no válida.");
}
function get_ficha( $id) {
// CONECCION DATABASE//
$database = new mysqli(HOST, USER, PASS, DBNAME);
if($database->connect_errno) {
die("No se pudo conectar a la base de datos");
}
mysqli_set_charset($database, "utf8");
//Sanitize ipnut y preparar query
if( is_array($id) ) {
$id = array_map('intval', $id);
$promo = "WHERE `ID` IN (" . implode( ',', $id ) . ")";
} else {
$id = intval($id);
$promo = "WHERE `ID` = " . $id;
}
if ( $result = $database->query( "SELECT * FROM (ficha)" . $promo) ) {
if( $result->num_rows > 0 ) {
$promo = array();
while( $row = mysqli_fetch_array($result))
{
$id=$row['id'];
$nombre=$row['nombre'];
$icono=$row['ico_138'];
$promo[] = array(
'i'=> $id,
'n'=> $nombre,
'p'=> $icono
);
}
} else {
$promo = array(
);
}
$result->close();
} else {
$promo["success"] = false;
$promo["data"] = array(
'message' => $database->error
);
}
header('Content-type: application/json; charset=utf-8');
echo json_encode($promo, JSON_UNESCAPED_UNICODE);
$database->close();
}
exit();
You need to explode the get variable
get_ficha(explode(',', $_GET['h']));
Then in your function
if( is_array($id) && count($id) > 1) {
$id = array_map('intval', $id);
$promo = "WHERE `ID` IN (" . implode( ',', $id ) . ")";
} else {
$id = intval($id);
$promo = "WHERE `ID` = " . $id;
}

Make SOAP request and insert duplicate values on database

I make a soap request in php, and I get the response from request and insert the values of the response in my database. I use my browser to run the script but something strange happens when I copy the link to another tab and run it, because when I check my database the values are duplicate. Sometimes when run the script the values are not duplicate in my database at the moment, but the next day the values are duplicate, and I don't understand why.
soap_request.php
<?php
ini_set('default_charset','utf8');
$init_today = date("Y-m-d");
$xml = 'soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:def="http://****/definitions" xmlns:cul="http:/***/****/***">
<soapenv:Header>'....;
$soapUrl = "https://****/Culture"; // asmx URL of WSDL
$headers = array(
...
"SOAPAction: http://****/****/****/*****",
"Content-length: ".strlen($xml),
);
$url = $soapUrl;
// PHP cURL for https connection with auth
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
...
$response = curl_exec($ch);
curl_close($ch);
$string = str_replace(array('ns1:', 'ns2:', 'ns3:'), array('', '', ''), $response);
$content = new SimpleXMLElement($string);
$con = mysqli_connect("localhost","root","***","*****");
function insertEventId($con, $content){
$array_id = array();
foreach($content->xpath('//Event') as $header){
$result = ($header->xpath('Id'));
$event_id = (string) $result[0];
$sql = "INSERT INTO eventos_sapo (event_id) VALUES ('$event_id')";
if (mysqli_query($con, $sql)) {
echo $sql . "</br>";
//echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
array_push($array_id, $event_id);
}
return $array_id;
}
function insertTitulo($con, $content, $array_id){
$count = 0;
while($count < sizeof($array_id)){
foreach($array_id as $id){
$count_aux = 0;
foreach($content->xpath('//Event') as $header){
$result = ($header->xpath('Name')); // Should output 'something'.
if($result){
$titulo = (string) $result[0];
if($count == $count_aux){
$sql = "Update eventos_sapo set titulo='$titulo' where event_id='$id';";
mysqli_set_charset($con,"utf8");
if (mysqli_query($con, $sql)) {
echo $sql . "</br>";
//echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
}
}
$count_aux++;
}
$count++;
}
}
}
$array_id = insertEventId($con, $content);
insertTitulo($con, $content, $array_id);
Response of request:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://***/**/***" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns2="http://***.****.**/***/**" xmlns:ns3="http://**.**.**/**/**">
<SOAP-ENV:Body>
<ns1:GetAgendaV2Response>
<ns1:GetAgendaV2Result>
<ns1:Events>
<ns1:Event>
<ns1:Id>94343</ns1:Id>
<ns1:Name>Mexa-se Mais 2011 - Orientação no Jamor (BTT e Caminhada)</ns1:Name>
<ns1:Genre>
<ns1:Id>10</ns1:Id>
<ns1:Name>Outdoor</ns1:Name>
</ns1:Genre>
</ns1:Event>
<ns1:Event>
<ns1:Id>122611</ns1:Id>
<ns1:Name>«Memória da Politécnica: Quatro Séculos de Educação, Ciência e Cultura»</ns1:Name>
<ns1:Genre>
<ns1:Id>6</ns1:Id>
<ns1:Name>Exposições</ns1:Name>
</ns1:Genre>
</ns1:Event>
....

Categories