i am able to send sms via php but in that i have to mention mobile number everytime i want that with the same script i can send sms to the entries stored in my database .
here is my code:
<?php
//Your authentication key`enter code here`
$authKey = "API key";
//Multiple mobiles numbers separated by comma
$mobileNumber = "+919425386214";
//Sender ID,While using route4 sender id should be 6 characters long.
$senderId = "Social";
//Your message to send, Add URL encoding here.
$message = urlencode("Test message");
//Define route
$route = "04";
//Prepare you post parameters
$postData = array(
'authkey' => $authKey,
'mobiles' => $mobileNumber,
'message' => $message,
'sender' => $senderId,
'route' => $route
);
if (isset($_POST['submit']))
{
//API URL
$url="https://control.msg91.com/api/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);
echo $output;
}
?>
please help so that i can send sms to my clients whom contact no. are stored in my database
You need to do some query code to do it , for your help a sample code:-
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
$mobileNumber = '';
$conn = mysqli_connect('localhost','root','','database name') or die (mysqli_error()); // give connection credentials here
if($conn){
$query = "Select mobile_number From User"; // change table name and column name accordingly.
$result = mysqli_query($conn,$query) or die(mysqli_error($conn));
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$mobileNumber .= $row['mobile_number'].',';
}
}
}
$mobileNumber = substr($mobileNumber,0,strlen($mobileNumber)-1); // now you have all mobile numbers in , seperated form in this variable
Note:- You can add this code in your current php code and do changes accordingly and you will get the output what you want.
Related
I am using a class to send GCM based Push Notification from PHP. I downloaded this class from https://www.phpclasses.org/package/8987-PHP-Send-push-notifications-to-Android-and-iOS-devices.html
All things are working as expected but as the number of Android users has crossed 3K now sending push notification is taking very long time. It takes around 2 to 2 and a half hours to send Push Notification.
And I cannot refresh the page to even close the browser otherwise the operation gets aborted.
How can I increase the speed of sending Push Notification from my script.
The important part of code that I am using for sending Push Notification is give below:
if (isset($_POST['sendmessage']) && !empty($_POST['sendmessage'])) {
$errorvalid = array();
$success = TRUE;
$requiredFields = array("subject_notify" => "Please Enter Notify Subject.", "subject_main" => "Please Enter Main Subject.", "msg" => "Please Enter Message");
foreach ($requiredFields as $fld => $msg) {
$v = $_POST[$fld];
if (empty($v)) {
$success = false;
$errorvalid[$fld] = $msg;
} else {
$errorvalid[$fld] = '';
$$fld = $v;
}
}
if($success)
{
$get_result = mysql_query("SELECT ps_mobile_id, ps_service_type FROM push_service", $con);
$row_result = mysql_fetch_assoc($get_result);
$totalRows_row_result = mysql_num_rows($get_result);
echo "Total Records: ".$totalRows_row_result;
echo "<br/>";
//Set parameters to hold time out error
set_time_limit(0);
error_reporting(E_ALL);
//ob_implicit_flush(TRUE);
//ob_end_flush();
if($totalRows_row_result > 0) {
$push = new pushmessage();
do {
$MobID = $row_result['ps_mobile_id'];
$MobType = $row_result['ps_service_type'];
echo "Mobile ID: ".$MobID;
echo "<br/>";
if($MobType == 1)
{
//Android
$params = array("pushtype"=>"android", "msg"=>$msg, "registration_id"=>$MobID, "subject_main"=>$subject_main, "subject_notify"=>$subject_notify, );
$rtn = $push->sendMessage($params);
//Push the message
$rtn = $push->sendMessage($params);
}
else
{
//iOS
//$params = array("pushtype"=>"android", "msg"=>$msg, "registration_id"=>$MobID, //"subject_main"=>$subject_main, "subject_notify"=>$subject_notify, );
//$rtn = $push->sendMessage($params);
//Push the message
//$rtn = $push->sendMessage($params);
}
echo "<br/>";
print_r($rtn);
echo "<br/>";
//ob_flush(); //Push data to Browser
}while ($row_result = mysql_fetch_assoc($get_result));
//header("Location: index.php");
echo "<h2>Completed Sending Pusht Message</h2>";
echo "<br/><br/>";
echo "Rediricting.... Please wait....";
echo "<br/><br/>";
echo '<meta http-equiv="refresh" content="3;url=http://mypresence.in/pushtibooks/pushmsg/" />';
}
else
{
echo "NO Data";
}
}
}
TIA
Yogi Yang
You are sending push notification one by one . That's why it takes too much time. You can send group message using device id. Check this documentation .
Use below code for sending push notification to android. Same way you can do this on iOS also.
//For andriod
$get_result = mysql_query("SELECT ps_mobile_id FROM push_service where ps_service_type = 1", $con);
// $row_result = mysql_fetch_assoc($get_result);
$totalRows_row_result = mysql_num_rows($get_result);
$MobIDs=array();
while($row = mysql_fetch_assoc($get_result)){
$MobIDs[] = $row;
}
$params = array("pushtype"=>"android", "msg"=>$msg, "subject_main"=>$subject_main, "subject_notify"=>$subject_notify, );
$rtn = $push->sendMessageAndroid($MobIDs, $params)
and sendMessageAndroid($registration_id, $params)
public $androidAuthKey = "Android Auth Key Here";
public $iosApnsCert = "./certification/xxxxx.pem";
/**
* For Android GCM
* $params["msg"] : Expected Message For GCM
*/
private function sendMessageAndroid($registration_id, $params) {
$this->androidAuthKey = "Android Auth Key Here";//Auth Key Herer
## data is different from what your app is programmed
$data = array(
'registration_ids' => array($registration_id),
'data' => array(
'gcm_msg' => $params["msg"]
)
);
$headers = array(
"Content-Type:application/json",
"Authorization:key=".$this->androidAuthKey
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$result = curl_exec($ch);
//result sample {"multicast_id":6375780939476727795,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1390531659626943%6cd617fcf9fd7ecd"}]}
//http://developer.android.com/google/gcm/http.html // refer error code
curl_close($ch);
$rtn["code"] = "000";//means result OK
$rtn["msg"] = "OK";
$rtn["result"] = $result;
return $rtn;
}
Please note that: Don't send more than 1000 device id per request. If you have more than 1000 users. then slice your MobIDs with a size less than 1000
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);
I'm using Quickblox to send push notifications to iPhone users. I created PHP functions for session and creating a user and API is working fine, but testing sending a push notification, I got an error on Dashboard/Queue: "incorrect event" on the message column. The event is created but never arrived.
The response of the API is OK, like the documentation.
I don't know why I got that error.
This is my code:
if (isset($_POST['mensaje'])) {
// Quickblox user Sign Up
$session = createSession( . . . , '...', '...', '...', '...');
$token = $session->token;
$group = '...'; // Hardcoded only for testing
$resp = sendQBPush($_POST['mensaje'], $group, $token);
}
and the function:
function sendQBPush($msg, $group, $token)
{
if (!$msg) {
return false;
}
$message = base64_encode($msg);
// Build post body
$post_body = array(
'event' => array(
'notification_type' => 'push',
'environment' => 'production',
'user' => array(
'tags' => array(
'any' => $group
)
) ,
'push_type' => 'apns',
'message' => 'payload=' . $message
)
);
$request = json_encode($post_body);
$ch = curl_init('http://api.quickblox.com/events.json');
curl_setopt($ch, CURLOPT_POST, true); // Use POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $request); // Setup post body
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'QuickBlox-REST-API-Version: 0.1.0',
'QB-Token: ' . $token
));
$resultJSON = curl_exec($ch);
$responseJSON = json_decode($resultJSON);
echo $resultJSON;
// Check errors
if ($responseJSON) {
return $responseJSON;
}
else {
$error = curl_error($curl) . '(' . curl_errno($curl) . ')';
return $error;
}
// Close connection
curl_close($curl);
}
Thanks for your help
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.
I have already tried below code,
function upload_content(){
// Authorization info
$tumblr_email = 'email-address#host.com';
$tumblr_password = 'secret';
// Data for new record
$post_type = 'text';
$post_title = 'Host';
$post_body = 'This is the body of the host.';
// Prepare POST request
$request_data = http_build_query(
array(
'email' => $tumblr_email,
'password' => $tumblr_password,
'type' => $post_type,
'title' => $post_title,
'body' => $post_body,
'generator' => 'API example'
)
);
// Send the POST request (with cURL)
$c = curl_init('api.tumblr.com/v2/blog/gurjotsinghmaan.tumblr.com/post');
//api.tumblr.com/v2/blog/{base-hostname}/post
//http://www.tumblr.com/api/write
//http://api.tumblr.com/v2/blog/{base-hostname}/posts/text?api_key={}
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, $request_data);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($c);
$status = curl_getinfo($c, CURLINFO_HTTP_CODE);
curl_close($c);
// Check for success
if ($status == 201) {
echo "Success! The new post ID is $result.\n";
} else if ($status == 403) {
echo 'Bad email or password';
} else {
echo "Error: $result\n";
}
}
You need to use the proper Tumblr endpoint:
http://www.tumblr.com/api/write
I'm pretty sure the others won't work.
Obviously make sure that your user and pass are correct, other than that, this looks fine - it's pretty much exactly what I'd write.