message send by twice while calling this function in codeigniter - php

When I call the function below, the field in my database gets the responses as send (only one time), but when I check the mobile it has sent two equal messages at a time.
public function sendverifymsg($phone, $verifycode) {
$user = "xx";
$password = "xx";
$api_id = "xx";
$baseurl = "http://promo.blastsms.in/sendsms.jsp?";
$text = urlencode("Thank you for registering with CARE MY KIDEE.. VERIFY CODE =" . $verifycode . "Please verify your mobile number immedi`enter code here`ately for our value added services.... ");
$version = "3";
//Define header array for cURL requestes
$header = array('Contect-Type:application/xml', 'Accept:application/xml');
// auth call
$url = "$baseurl/&user=$user&password=$password&mobiles=$phone&sms=$text&senderid=$api_id&version=$version";
//Define http request nouns
$ls = $url . "landscapes";
//Initialise cURL object
$ch = curl_init();
//Set cURL options
curl_setopt_array($ch, array(
CURLOPT_HTTPHEADER => $header, //Set http header options
CURLOPT_URL => $ls, //URL sent as part of the request
CURLOPT_NOBODY => 1,
CURLOPT_FAILONERROR => TRUE,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC, //Set Authentication to BASIC
CURLOPT_USERPWD => $user . ":" . $password, //Set username and password options
CURLOPT_HTTPGET => TRUE //Set cURL to GET method
));
//Define variable to hold the returned data from the cURL request
$data = curl_exec($ch);
if (curl_exec($ch) !== FALSE) {
$matches = array();
// we use ? because we want to stop at first </error-description>
// we use preg_match because we want only one error-description text
preg_match('/<error-description>(.+?)<\/error-description>/', $data, $matches);
$errorDescription = isset($matches[1]) ? $matches[1] : '';
if ($errorDescription) {
$sess_id = $this->session->userdata('id');
$this->generatedate_model->sendsmsdetails($errorDescription, $phone, $sess_id);
} else {
$errorDescription = 'verify';
$sess_id = $this->session->userdata('id');
$this->generatedate_model->sendsmsdetails($errorDescription, $phone, $sess_id);
}
return true;
} else {
$matches = array();
// we use ? because we want to stop at first </error-description>
// we use preg_match because we want only one error-description text
preg_match('/<error-description>(.+?)<\/error-description>/', $data, $matches);
$errorDescription = isset($matches[1]) ? $matches[1] : '';
// $errorDescription = "failed";
$sess_id = $this->session->userdata('id');
$this->generatedate_model->sendsmsdetails($errorDescription, $phone, $sess_id);
return false;
}
//Close cURL connection
curl_close($ch);
}

Try it
$data = curl_exec($ch);
if (curl_exec($ch) !== FALSE) {
Modify It
$data = curl_exec($ch);
if ($data !== FALSE) {
You are execute tow time CURL

Related

How do i fix my JSON format by using php

I try to send json format to my android app , but i find that my json format is uncorrect.
{data={"image":"http:\/\/www.androidhive.info\/wp-content\/uploads\/2016\/01\/Air-1.png","message":{"chat_room_id":"","created_at":"2017-03-22 3:34:30","message_id":"","message":"77"},"user":{"user_id":null,"gcm_registration_id":null,"name":null,"created_at":null,"email":null}}, flag=0, title=Google Cloud Messaging, is_background=false}
I set the data like this:
$app->post('/users/send_to_all',
function() use ($app) {
$response = array();
verifyRequiredParams(array('user_id', 'message'));
require_once __DIR__ . '/../libs/gcm/gcm.php';
require_once __DIR__ . '/../libs/gcm/push.php';
$db = new DbHandler();
$user_id = $app->request->post('user_id');
$message = $app->request->post('message');
require_once __DIR__ . '/../libs/gcm/gcm.php';
require_once __DIR__ . '/../libs/gcm/push.php';
$gcm = new GCM();
$push = new Push();
//get the user using userid
$user = $db->getUser($user_id);
//creating tmp message , skipping database insertion
$msg = array();
$msg['message'] = $message;
$msg['message_id'] = '';
$msg['chat_room_id'] = '';
$msg['created_at'] = date('Y-m-d G:i:s');
$data = array();
$data['user'] = $user;
$data['message'] = $msg;
$data['image'] = 'http://www.androidhive.info/wp-content/uploads/2016/01/Air-1.png';
$push->setTitle("Google Cloud Messaging");
$push->setIsBackground(FALSE);
$push->setFlag(PUSH_FLAG_USER);
$push->setData($data);
//sending message to topic `global`
//on the device every user should subscribe to `global` topic
$gcm->sendToTopic('global', $push->getPush());
$response['user'] = $user;
$response['error'] = false;
echoRespnse(200, $response);
});
Here is my Push.php about getPush():
public function getPush() {
$res = array();
$res['title'] = $this->title;
$res['is_background'] = $this->is_background;
$res['flag'] = $this->flag;
$res['data'] = $this->data;
return $res;
}
Here is my Gcm.php about sendToTopic:
//sending message to a topic by topic id
public function sendToTopic($to, $message) {
$fields = array(
'to' => '/topics/' . $to,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
I'm really not familiar with php , how do i fix the JSON format ?
Any help would be appreciated , thanks in advance !
I update my question , i find json_encode in my Gcm.php:
It's on curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
class GCM {
//constructor
function __construct() {
}
//sending push message to single user by gcm registration id (array 最後面有, 待看)
public function send($to, $message) {
$fields = array(
'to' => $to,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
//sending message to a topic by topic id
public function sendToTopic($to, $message) {
$fields = array(
'to' => '/topics/' . $to,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
//sending push message to multiple users by gcm registration ids
public function sendMultiple($registration_ids, $message) {
$fields = array(
'registration_ids' => $registration_ids,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
//function makes curl request to gcm servers (__DIR__ 待看)
private function sendPushNotification($fields) {
//include config
include_once __DIR__ . '/../../include/config.php';
//Set POST variable
//$url = 'https://gcm-http.googleapis.com/gcm/send';
$url='https://fcm.googleapis.com/fcm/send';
$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);
return $result;
}
}
?>
It's still let my json format incorrect , how do i fix ?
PHP has some built-in json functions, you need json_encode() and json_decode().
For example this code:
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
Will print:
{"a":1,"b":2,"c":3,"d":4,"e":5}
Here's the link to documentation for json_encode() and for the entire json in php documentation.
Hope this helps.
Your JSON is invalid. try:
{"data":{"image":"http:\/\/www.androidhive.info\/wp-content\/uploads\/2016\/01\/Air-1.png","message":{"chat_room_id":"","created_at":"2017-03-22 3:34:30","message_id":"","message":"77"},"user":{"user_id":null,"gcm_registration_id":null,"name":null,"created_at":null,"email":null}}, "flag":0, "title":"Google Cloud Messaging", "is_background":false}
Notice ive replaced usage of = with : and wrapped keys and strings in quotes (")
To get it into a nice json string with php you need to build your array correctly first. Possible way is to setup a response array and then you can json_encode() it.
$response =[
'data' => $data,
'flag' => 0,
'title' => 'Google Cloud Messaging',
'is_background' => false.
];
now you can
json_encode($response);

PHP : server error

I have a PHP code for sending OTP, When i execute it in my local server its works well. But when i run this code after changing it from my local to server by changing host name etc, i am getting 500 internal server error. I don't know where i am going wrong. Any solution will be apreciated. Thank you
<?php
include './include/DbHandler.php';
$db = new DbHandler();
$response = array();
// echo $_POST['mobile'];
if (isset($_POST['mobile']) && $_POST['mobile'] != '') {
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$otp = rand(100000, 999999);
$res = $db->createUser($name, $email, $mobile, $otp);
if ($res == USER_CREATED_SUCCESSFULLY) {
// send sms
sendSms($mobile, $otp);
$response["error"] = false;
$response["message"] = "SMS request is initiated! You will be receiving it shortly.";
} else if ($res == USER_CREATE_FAILED) {
$response["error"] = true;
$response["message"] = "Sorry! Error occurred in registration.";
} else if ($res == USER_ALREADY_EXISTED) {
$response["error"] = true;
$response["message"] = "Mobile number already existed!";
}
} else {
$response["error"] = true;
$response["message"] = "Sorry! mobile number is not valid or missing.";
}
echo json_encode($response);
function sendSms($mobile, $otp) {
$otp_prefix = ':';
//Your message to send, Add URL encoding here.
$message = urlencode("Hello Your OPT is '$otp_prefix $otp'");
$response_type = 'json';
//Define route
$route = "4";
//Prepare you post parameters
$postData = array(
'authkey' => AUTH_KEY,
'mobiles' => $mobile,
'message' => $message,
'sender' => SENDER_ID,
'route' => $route,
'response' => $response_type
);
//API URL
$url = "https://control.otp.com/sendhttp.php";
// init the resource
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postData
//,CURLOPT_FOLLOWLOCATION => true
));
//Ignore SSL certificate verification
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
//get response
$output = curl_exec($ch);
//Print error if any
if (curl_errno($ch)) {
echo 'error:' . curl_error($ch);
}
curl_close($ch);
}
?>
I dont think the 500 error comes from your code. That's likely an Apache config related problem. Possibly a stray .htaccess or php.ini got uploaded, or is syntactically wrong for the version of Apache you have on the server.

How to POST via Reddit API (addcomment)

I've been able to successfully log a user in and return their details. The next step is to get them to post a comment via my app.
I tried modifying code from the reddit-php-sdk -- https://github.com/jcleblanc/reddit-php-sdk/blob/master/reddit.php -- but I can't get it to work.
My code is as follows:
function addComment($name, $text, $token){
$response = null;
if ($name && $text){
$urlComment = "https://ssl.reddit.com/api/comment";
$postData = sprintf("thing_id=%s&text=%s",
$name,
$text);
$response = runCurl($urlComment, $token, $postData);
}
return $response;
}
function runCurl($url, $token, $postVals = null, $headers = null, $auth = false){
$ch = curl_init($url);
$auth_mode = 'oauth';
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 10
);
$headers = array("Authorization: Bearer {$token}");
$options[CURLOPT_HEADER] = false;
$options[CURLINFO_HEADER_OUT] = false;
$options[CURLOPT_HTTPHEADER] = $headers;
if (!empty($_SERVER['HTTP_USER_AGENT'])){
$options[CURLOPT_USERAGENT] = $_SERVER['HTTP_USER_AGENT'];
}
if ($postVals != null){
$options[CURLOPT_POSTFIELDS] = $postVals;
$options[CURLOPT_CUSTOMREQUEST] = "POST";
}
curl_setopt_array($ch, $options);
$apiResponse = curl_exec($ch);
$response = json_decode($apiResponse);
//check if non-valid JSON is returned
if ($error = json_last_error()){
$response = $apiResponse;
}
curl_close($ch);
return $response;
}
$thing_id = 't2_'; // Not the actual thing id
$perma_id = '2daoej'; // Not the actual perma id
$name = $thing_id . $perma_id;
$text = "test text";
$reddit_access_token = $_SESSION['reddit_access_token'] // This is set after login
addComment($name, $text, $reddit_access_token);
The addComment function puts the comment together according to their API -- http://www.reddit.com/dev/api
addComment then calls runCurl to make the request. My guess is that the curl request is messed up because I'm not receiving any response whatsoever. I'm not getting any errors so I'm not sure what's going wrong. Any help would really be appreciated. Thanks!
If you are using your own oAuth solution, I would suggest using the SDK as I said in my comment, but extend it to overwrite the construct method.
class MyReddit extends reddit {
public function __construct()
{
//set API endpoint
$this->apiHost = ENDPOINT_OAUTH;
}
public function setAuthVars($accessToken, $tokenType)
{
$this->access_token = $accessToken;
$this->token_type = $tokenType;
//set auth mode for requests
$this->auth_mode = 'oauth';
}
}
You just need to make sure that you call setAuthVars before running any api calls.

sending bulk sms stops in middle

Guys i have an issue in the following code. I need to send bulk sms to 24,000 mobile numbers. But if i send it after 150 number send it shows me an Internal server error and stop send other following numbers. Kindly go through the code given below and reply the positive code that can really help me.
<?php
//Code using fopen
//Change your configurations here.
//---------------------------------
$username = "username";
$api_password = "api_password";
$sender = "sender";
$domain = "domain";
$priority = "1";// 1-Normal,2-Priority,3-Marketing
$method = "POST";
//---------------------------------
for ($i = 0; $i < $var; $i++) {
if (isset($_REQUEST['send'])) {
$mobile = $explode_num[$i];
$lenthof_number = strlen($mobile);
if ($lenthof_number >= 10) {
$message = $_REQUEST['message'];
$username = urlencode($username);
$password = urlencode($api_password);
$sender = urlencode($sender);
$message = urlencode($message);
$parameters = "username=$username&api_password=$api_password&sender=$sender&to=$mobile&message=$message&priority=$priority";
if ($method == "POST") {
$opts = array(
'http' => array(
'method' => "$method",
'content' => "$parameters",
'header' => "Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
$fp = fopen("http://$domain/pushsms.php", "r", false, $context);
} else {
$fp = fopen("http://$domain/pushsms.php?$parameters", "r");
}
$response = stream_get_contents($fp);
fpassthru($fp);
fclose($fp);
if ($response == "")
echo "Process Failed, Please check domain, username and password.";
else
echo "$response";
}//third if
}//second if
}//first if
}//main for
?>
Probably your page exeeded the max execution time. Put following code on top of page and try:
ini_set("memory_limit","128M");
//ini_set("memory_limit","256M");
//this sets it unlimited
ini_set("max_execution_time",0);
Add this on the top of your PHP Script
<?php
set_time_limit(0);

What request does the PHP cURL function produce?

I am currently writing an C# windows service, which integrates with a PHP page. I have an example of code making the request in PHP which is below however I have never developed in PHP and don't understand how the cURL function performs the request.
Is there anyway to retrieve the request which is being sent? Or can anyone provide an example of how the request would look and how the request is sent so I can replicate the request in C#.
Thank you for any help.
public function api(/* polymorphic */) {
$args = func_get_args();
if (is_array($args[0])) {
$serviceId = $this->getApiServiceId($args[0]["method"]);
unset($args[0]["method"]);
$args[0]["serviceId"] = $serviceId;
$args[0]["dealerId"] = $this->dealerId;
$args[0]["username"] = $this->username;
$args[0]["password"] = $this->password;
$args[0]["baseDomain"] = $this->baseDomain;
return json_decode($this->makeRequest($args[0]));
} else {
throw Exception("API call failed. Improper call.");
}
}
protected function makeRequest($params, $ch=null) {
if (!$ch) {
$ch = curl_init();
}
$opts = self::$CURL_OPTS;
if ($this->useFileUploadSupport()) {
$opts[CURLOPT_POSTFIELDS] = $params;
} else {
$opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
}
// disable the 'Expect: 100-continue' behaviour. This causes CURL to wait
// for 2 seconds if the server does not support this header.
if (isset($opts[CURLOPT_HTTPHEADER])) {
$existing_headers = $opts[CURLOPT_HTTPHEADER];
$existing_headers[] = 'Expect:';
$opts[CURLOPT_HTTPHEADER] = $existing_headers;
} else {
$opts[CURLOPT_HTTPHEADER] = array('Expect:');
}
curl_setopt_array($ch, $opts);
$result = curl_exec($ch);
if ($result === false) {
$e = new WPSApiException(array(
'error_code' => curl_errno($ch),
'error' => array(
'message' => curl_error($ch),
'type' => 'CurlException',
),
));
curl_close($ch);
throw $e;
}
curl_close($ch);
return $result;
}
Add the option CURLINFO_HEADER_OUT to curl handle, then call curl_getinfo on it after execing.
As in:
//...
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
//...
curl_exec($ch);
//...
$header = curl_getinfo(CURLINFO_HEADER_OUT);
echo $header;

Categories