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);
Related
I'm try to make a Telegram bot that'll connect to an RCON, but at the moment I'm stuck in the usage of the sessions, seems like they aren't saved.
This is my code so far:
<?php
define('BOT_TOKEN', 'xx:xxxxxx');
define('API_URL', 'https://api.telegram.org/bot'.BOT_TOKEN.'/');
//Start session
session_set_cookie_params(3600, "/");
session_start();
//read incoming info and grab the chatID
$content = file_get_contents("php://input");
$update = json_decode($content, true);
$chatID = $update["message"]["chat"]["id"];
$message = $update["message"]["text"];
$reply = "";
if (isset($_SESSION['AskIP'])){
$_SESSION = array('AskPort' => true,
'ip' => $message);
$reply = "Saved IP: ". $message ."Write the port";
}
else if (isset($_SESSION['AskPort'])){
$ip = $_SESSION['ip'];
$_SESSION = array('connected' => true,
'ip' => $ip,
'port' => $message);
$reply = "Now you are connected the rcon (".$_SESSION['ip']. ":". $_SESSION['port'].")! Type /disconnect to disconnect from the rcon!";
}
else if (substr($message, 0, 11) === "/disconnect" && strlen($message) == 11 && isset($_SESSION['connected'])){
$_SESSION['connected'] = false;
$reply = "Disconnected from". $_SESSION['ip'] .":". $_SESSION['port'];
$_SESSION = array();
session_destroy();
}
else if (substr($message, 0, 5) === "/rcon" && strlen($message) == 5) {
$_SESSION = array('AskIP' => true);
$reply = "Write the Server IP";
}
if (empty($reply))
return;
$sendto = API_URL."sendmessage?chat_id=".$chatID."&text=".$reply;
file_get_contents($sendto);
?>
At the momement it only works when you type /rcon (and the replies "Write the IP" but after that no answer, the privacy settings are already disabled.
I ended up just by using mysql.
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 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.
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
I want to send the request to another site with GET request and should return a string value. I am using the following cURL code to achieve this but its getting failed.
$user = 'username';
$password = 'password';
$sender_id = 'myid';
$sender_mobile = mobile number;
$message_text = 'Hi Testing SMS';
$priority = 'ndnd';
$sms_type = 'normal';
$redirect_link = "http://bhashsms.com/api/sendmsg.php?user=$user&pass=$password&sender=$sender_id&phone=$sender_mobile&text=$message_text&priority=$priority&stype=$sms_type";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$redirect_link);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$output=curl_exec($ch);
if($output == false)
{
echo "Error Number:".curl_errno($ch)."<br>";
echo "Error String:".curl_error($ch);
}
$info = curl_getinfo($ch);
curl_close($ch);
But if i use the header its sending successfully the following is using header
$user = 'username';
$password = 'password';
$sender_id = 'myid';
$sender_mobile = mobile number;
$message_text = 'Hi Testing SMS';
$priority = 'ndnd';
$sms_type = 'normal';
$redirect_link = "http://bhashsms.com/api/sendmsg.php?user=$user&pass=$password&sender=$sender_id&phone=$sender_mobile&text=$message_text&priority=$priority&stype=$sms_type";
header("Location:$redirect_link");
where am I going wrong!!!
You have an error on $sender_mobile = mobile number; should be like this $sender_mobile = 'mobile number';