CURL - sending variables with GET not working - php

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';

Related

Google Recaptcha error, logs in without completing puzzle but shows tick

I have built a log in system and I am adding google recaptcha for security. I am getting an error on this line: $result = json_decode($url, TRUE);
The error says;
failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request.
This is my first time using recaptcha and I am not sure if this is a common mistake.
<?php
$secret = '*****';
$response = $_POST['g-recaptcha-response'];
$remoteip = $_SERVER['REMOTE_ADDR'];
$captcha = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$response&remoteip=$remoteip");
$result = json_decode($url, TRUE);
$username;
$password;
$captcha;
if (isset($_POST['username']))
$username = $_POST['username'];
if (isset($_POST['password']))
$password = $_POST['password'];
if (isset($_POST['g-recaptcha-response']))
$captcha = $_POST['g-recaptcha-response'];
if (!$captcha) {
echo '<p class="error-message">Please Complete The Captcha!</p>';
header("location: login.php");
exit;
}
$response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=6LfG-S8UAAAAAIqW1sBE31yMPyO4zeqOCgDzL1mA&response=" . $captcha . "&remote=" . $_SERVER['REMOTE_ADDR']), true);
if ($response['success'] == false) {
echo '<p class="error-message">Please Fill Captcha!</p>';
} else {
echo '<p class="error-message2">Welcome</p>';
}
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$q = $handler->prepare('SELECT * FROM users WHERE username = ?');
$q->execute(array($username));
$result = $q->fetch(PDO::FETCH_ASSOC);
if ($result !== false) {
$hash_pwd = $result['password'];
$hash = password_verify($password, $hash_pwd);
if ($hash) {
$_SESSION['username'] = $username;
header("location:index.php");
return;
} else {
echo '<p class="error-message3"><br><br>You have ented an incorrect login!<br>Please try again</p>';
}
}
}
?>
If this really is your complete code:
It seems you are using $url (in the line $result = ...) without having initialized it before.
Additionally, I would expect that a variable with name $url contains an URL, and URLs are not in JSON format, so this raises some alarm signs. You eventually do not want to JSON-parse an URL, but instead parse what this URL returns when calling it.
Secondly, sometimes the line numbers within error messages or warnings are misleading. I highly doubt that the error you have mentioned (HTTP request failed) is related to json_decode(). json_decode(), as the name implies, just parses a string in JSON format, but does not load anything via HTTP.
So the error message probably comes from the line above ($captcha = file_get_contents(...);). I suppose that the URL you give there is wrong, or that Google refuses the request for another reason.
The first thing I would do is putting that URL into a variable and print it out (e.g. by using error_log()).
If that does not lead to the source of the problem, I would copy that URL (not from the code, but from the output produced by error_log()) and paste it directly into the address bar of a new browser window. If this yields the expected result (you should see Google's answer to the request in the browser window), the error is in your code. Otherwise, the error is in the URL.
<?php
session_start();
error_reporting(E_ALL);
try {
$ini = parse_ini_file("/var/www/admin.ini");
$user = $ini['user'];
$pass = $ini['pass'];
$name = $ini['name'];
$host = $ini['host'];
$handler = new PDO('mysql:host='.$host.'; dbname='.$name, $user, $pass);
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
error_log($e);
echo $e->getMessage();
}
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://www.google.com/recaptcha/api/siteverify',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => [
'secret' => '********',
'response' => $_POST['g-recaptcha-response'],
],
]);
$response = json_decode(curl_exec($curl));
if (!$response->success) {
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$q = $handler->prepare('SELECT * FROM users WHERE username = ?');
$q->execute(array($username));
$result = $q -> fetch(PDO::FETCH_ASSOC);
if ($result !== false) {
$hash_pwd = $result['password'];
$hash = password_verify($password, $hash_pwd);
if ($hash) {
$_SESSION['username'] = $username;
header("location:index.php");return;
}
else {echo '<p class="error-message3"><br><br>You have ented an incorrect login!<br>Please try again</p>';
}
}
}
}
?>

GCM Push notification sending taking very long time in PHP

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

"Member 0 does not have permission to get company" error when trying to access LinkedIn company updates

I've had the client approve my user as an administrator after I created my application through LinkedIn's Developer backend. I even had the client create their OWN application and provide me the client keys for it, however I'm getting the same error message every time when trying to pull the company updates:
"Member 0 does not have permission to get company 1311XXX"
Here's my code for that page:
$config['base_url'] = 'http://www.hiddenlink.com/resources/li-oauth-src/auth.php';
$config['callback_url'] = 'http://www.hiddenlink.com/resources/li-oauth-src/demo.php';
$config['linkedin_access'] = '770lXXXXXXXXXX';
$config['linkedin_secret'] = 'hcxpOtXXXXXXXXXX';
include_once "linkedin.php";
# First step is to initialize with your consumer key and secret. We'll use an out-of-band oauth_callback
$linkedin = new LinkedIn($config['linkedin_access'], $config['linkedin_secret'], $config['callback_url'] );
//$linkedin->debug = true;
if (isset($_REQUEST['oauth_verifier'])){
$_SESSION['oauth_verifier'] = $_REQUEST['oauth_verifier'];
$linkedin->request_token = unserialize($_SESSION['requestToken']);
$linkedin->oauth_verifier = $_SESSION['oauth_verifier'];
$linkedin->getAccessToken($_REQUEST['oauth_verifier']);
$_SESSION['oauth_access_token'] = serialize($linkedin->access_token);
header("Location: " . $config['callback_url']);
exit;
}
else{
$linkedin->request_token = unserialize($_SESSION['requestToken']);
$linkedin->oauth_verifier = $_SESSION['oauth_verifier'];
$linkedin->access_token = unserialize($_SESSION['oauth_access_token']);
}
$json_response = $linkedin->getCompanyUpdates("1311XXX");
$json = json_decode($json_response);
echo "<pre>";
print_r($json);
echo "</pre>";
for($x = 0; $x < 2; $x++){
$json_value = $json->values[$x];
$articleURL = $json_value->updateContent->companyStatusUpdate->share->content->eyebrowUrl;
$postTitle = $json_value->updateContent->companyStatusUpdate->share->content->title;
$description = htmlspecialchars($json_value->updateContent->companyStatusUpdate->share->content->description);
$timestamp = $json_value->updateContent->companyStatusUpdate->share->timestamp;
echo '<pre>';
print_r($description);
echo '<br />';
print_r($articleURL);
echo '<br />';
print_r($postTitle);
print_r(date("jS M, Y", $timestamp));
echo '</pre>';
}
Here is the code for the getCompanyUpdates function being called for the json_response variable:
function getCompanyUpdates($id){
$updateURL = $this->base_url . "/v1/companies/" . $id . "/updates?format=json";
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->access_token, "GET", $updateURL);
$request->sign_request($this->signature_method, $this->consumer, $this->access_token);
$auth_header = $request->to_header("https://api.linkedin.com"); # this is the realm
$response = $this->httpRequest($updateURL, $auth_header, "GET");
return $response;
}
I have zero clue what I'm doing wrong, but it's clear I'm doing something wrong. Any help would be much appreciated
You don't seem to be explicitly passing a scope value anywhere in your oauth workflow, so I can only presume you are relying on your LinkedIn application's default scope values to be configured correctly.
Check to make sure you are requesting the rw_company_admin member permission when attempting to make that API call.

message send by twice while calling this function in codeigniter

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

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);

Categories