I have this condition to scheduled my sms. (ERROR) but the sms I'm using is POST method I need to be automated. And send sms to the number of the current id. I don't know how to get the number of the current id and send the message. Here is my code:
$duedate = "";
$date_now = date("Y-m-d");
date_default_timezone_set('Asia/Manila');
$date_now = strtotime($date_now);
$duedate = strtotime($duedate);
if ($duedate <= $date_now) {
function itexmo($number, $message, $apicode) {
$url = 'https://www.itexmo.com/php_api/api.php';
$itexmo = array('1' => $number, '2' => $message, '3' => $apicode);
$param = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($itexmo),
),
);
$context = stream_context_create($param);
return file_get_contents($url, false, $context);
}
if ($_POST) {
$number = $number;
$name = $name;
$api = "API";
$text = $name." : ".$number;
if (!empty($_POST['name']) && ($_POST['number']) && ($_POST['msg'])) {
$result = itexmo($number, $text, $api);
if ($result == "") {
echo "iTexMo: No response from server!!!
Please check the METHOD used (CURL or CURL-LESS). If you are using CURL then try CURL-LESS and vice versa.
Please CONTACT US for help. ";
} elseif ($result == 0) {
echo "Message Sent!";
} else {
echo "Error Num ". $result . " was encountered!";
}
}
}
}
It is better to use PHP cURL than stream_context_create and file_get_contents.
Take a look at below code, it should help you.
function itexmo($number,$message,$apicode)
{
$url = 'https://www.itexmo.com/php_api/api.php';
$postValues = http_build_query(['1' => $number, '2' => $message, '3' => $apicode])
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postValues);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"cache-control: no-cache",
"content-type: application/x-www-form-urlencoded"
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close ($ch);
return $response;
}
You can learn more PHP cURL.
Related
I'm trying to add an array of players_id to send to push notification to specific mobiles, but I keep getting the error "Incorrect player_id format in include_player_ids (not a valid UUID)"
if ($cons) {
$dado1 = array();
$dado2 = array();
while ($row = sqlsrv_fetch_array($cons, SQLSRV_FETCH_ASSOC)) {
$dado1 = array(
$row['funcionarioId']
);
array_push($dado2, $dado1);
}
//echo json_encode($dado2);
} else {
$dado2 = array();
array_push($dado2, $dado1);
$retornoVazio = array("Retorno" => $dado2);
EnviaEmailComErro($sql, sqlsrv_errors(), "Consulta_NFCe - ConsultaDados");
array_push($dado2, array("Success" => "0", "Error" => "1"));
echo json_encode($retornoVazio);
}
function sendMessage($produto, $mesa, $comanda, $garcom, $dado2)
{
$content = array(
"en" => " Garçom $garcom \n o pedido: $produto está pronto!\n mesa: $mesa \n comanda: $comanda",
);
**That where it should add the IDS**
$fields = array(
'app_id' => "***",
'include_player_ids' => array($dado2),
'channel_for_external_user_ids' => 'push',
'data' => array("foo" => "bar"),
'contents' => $content
);
$fields = json_encode($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
'Authorization: Basic ***'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$response = sendMessage($produto, $mesa, $comanda, $garcom, $dado2);
$return["allresponses"] = $response;
$return = json_encode($return);
the variable $fields print
{"app_id":"***",
"include_player_ids":[
[
["2610ec53-"],
["045eac07-"],
["8fb19bd9-"]
]
]"
And $response:
{"errors":["Incorrect player_id format in include_player_ids (not a valid UUID): [[\"2610ec53-\"], [\"045eac07-\"], [\"8fb19bd9-\"]]"]}
"The players ID are complete in the code, but I deleted it."
In the if ($cons) { you are pushing all sorts of stuff into arrays, simplify it to
if ($cons) {
$dado2 = array();
while ($row = sqlsrv_fetch_array($cons, SQLSRV_FETCH_ASSOC)) {
$dado2[] = $row['funcionarioId'];
}
} else {
And in the function make this change
'include_player_ids' => $dado2,
I am developing a facebook chatbot. I am facing a issue which I cannot solve. I am developing this in laravel. Here I cannot get the postback payload. here is my code
public function index(Request $request) {
if ($request->hub_verify_token === $this->verifyToken) {
echo $request->hub_challenge;
exit;
}
$input = json_decode(file_get_contents("php://input"), true);
$senderId = $input['entry'][0]['messaging'][0]['sender']['id'];
$messageText = $input['entry'][0]['messaging'][0]['message']['text'];
$pageId = $input['entry'][0]['id'];
$accessToken = "access_token_that_got_from_fb";
//set Message
if($messageText != "") {
$answer = "Howdy! User";
}
if($messageText == "hello") {
$answer = 'Testing hello from bot';
}
foreach ($input['entry'][0]['messaging'] as $message) {
// When bot receive message from user
if (!empty($message['postback'])) {
$answer = 'got it tada';
}
}
//send message to facebook bot
$response = [
'recipient' => [ 'id' => $senderId ],
'message' => [ 'text' => $answer ] //json_encode($request->getContent())
];
$ch = curl_init('https://graph.facebook.com/v2.11/me/messages?access_token='.$accessToken);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($response));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
$result = curl_exec($ch);
curl_close($ch);
}
and my route is
Route::any('chatbot', 'ChatbotController#index');
here the message is working . but the postback payload request is not going to server. on the other hand using the same code in normal php file I am able to get postback paylod.
$hubVerifyToken = 'chatbot';
$accessToken = "access_token";
// check token at setup
if ($_REQUEST['hub_verify_token'] === $hubVerifyToken) {
echo $_REQUEST['hub_challenge'];
exit;
}
// handle bot's anwser
$input = json_decode(file_get_contents('php://input'), true);
$senderId = $input['entry'][0]['messaging'][0]['sender']['id'];
$messageText = $input['entry'][0]['messaging'][0]['message']['text'];
$postback = isset($input['entry'][0]['messaging'][0]['postback']['payload']) ? $input['entry'][0]['messaging'][0]['postback']['payload'] : '' ;
//set Message
if($messageText == "hi") {
$answer = "Hello";
}
if($messageText == "hello") {
$answer = "Hello there, welcome to Chatleads";
}
if($postback) {
$answer = "postback TADA";
}
//send message to facebook bot
$response = [
'recipient' => [ 'id' => $senderId ],
'message' => [ 'text' => $answer ]
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://graph.facebook.com/v2.11/me/messages?access_token=$accessToken");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($response));
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
How to solve this issue? can anyone show me a path?
Solved it by checking at laravel.log file.
$this->messageText = isset($this->input['entry'][0]['messaging'][0]['message']['text']) ? $this->input['entry'][0]['messaging'][0]['message']['text'] : '' ;
messageText should be like this. that's why its causing an error.
i am using following code to send gcm message using php and mysqldb i have successfully send the gcm message and received it on the device however the android guidelines state that gcm message should be send in batch of 1000 each http://developer.android.com/training/cloudsync/gcm.html#multicast
now my question is how can we send gcm messages in lots of 1000 to a database of say 10,000 registered users.
<?php
require 'connect.php';
function sendPushNotification($registration_ids, $message) {
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registration_ids,
'data' => $message,
);
define('GOOGLE_API_KEY', 'keys_value');
$headers = array(
'Authorization:key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
echo json_encode($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if($result === false)
die('Curl failed ' . curl_error());
curl_close($ch);
return $result;
}
$pushStatus = '';
if(!empty($_GET['push'])) {
$query = "SELECT gcm_regId FROM gcm_users";
if($query_run = mysql_query($query)) {
$gcmRegIds = array();
while($query_row = mysql_fetch_assoc($query_run)) {
array_push($gcmRegIds, $query_row['gcm_regId']);
}
}
$pushMessage = $_POST['message'];
if(isset($gcmRegIds) && isset($pushMessage)) {
$message = array('price' => $pushMessage);
$pushStatus = sendPushNotification($gcmRegIds, $message);
}
}
?>
<html>
<head>
<title>Google Cloud Messaging (GCM) Server in PHP</title>
</head>
<body>
<h1>Google Cloud Messaging (GCM) Server in PHP</h1>
<form method = 'POST' action = 'send_all.php/?push=1'>
<div>
<textarea rows = 2 name = "message" cols = 23 placeholder = 'Messages to Transmit via GCM'></textarea>
</div>
<div>
<input type = 'submit' value = 'Send Push Notification via GCM'>
</div>
<p><h3><?php echo $pushStatus ?></h3></p>
</form>
</body>
</html>
Make $gcmRegIds to be a 2D array and then foreach it to push msg:
if(!empty($_GET['push'])) {
$query = "SELECT gcm_regId FROM gcm_users";
if($query_run = mysql_query($query)) {
$gcmRegIds = array();
$i = 0;
while($query_row = mysql_fetch_assoc($query_run)) {
$i++;
$gcmRegIds[floor($i/1000)][] = $query_row['gcm_regId'];
}
}
$pushMessage = $_POST['message'];
if(isset($gcmRegIds) && isset($pushMessage)) {
$message = array('price' => $pushMessage);
$pushStatus = array();
foreach($gcmRegIds as $val) $pushStatus[] = sendPushNotification($val, $message);
}
}
Here is what i did for my scenario to resolve for FCM .You can also ignore some parts of the code
<?php
$saved_tokens=array(); // could be more than 1000 token the maximum size as per google FCM requirement
//$count=1;
$ID_SETS = array_chunk($saved_tokens, 1000); // make a group of 1000 items in each set
foreach ($ID_SETS as $value_ids) {
// echo "Chunk ".$count."<br>";
sendFCM_Notification("what_ever_parameter_data",$value_ids);
foreach ($value_ids as $value_i ) { // you can remove this part its not neccessary
//echo " ---- contents of Chunk ".$count ."with Value".$value_i."<br>";
}
// $count++;
}
function sendFCM_Notification($what_ever_parameter,$reg_ids_array){
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
'registration_ids' => $reg_ids_array,
'data' => $what_ever_parameter
);
$headers = array(
'Authorization:key = YOUR_KEY ',
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
?>
I'm a beginner in PHP, so maybe someone could help to fix this ?
My web application is showing Google PageInsights API error..
Here's the code, I tried to change version to /v2/, but it still didn't work..
public function getPageSpeed($domain, $api = "")
{
try
{
$callback_url = "https://www.googleapis.com/pagespeedonline/v1/runPagespeed?";
$data = array(
'url' => 'http://' . $domain,
'key' => (empty($api) ? $_SESSION['GOOGLEAPI_SERVERKEY'] : $api),
'fields' => 'score,pageStats(htmlResponseBytes,textResponseBytes,cssResponseBytes,imageResponseBytes,javascriptResponseBytes,flashResponseBytes,otherResponseBytes)'
);
$curl_response = $this->curl->get($callback_url . http_build_query($data, '', '&'));
if ($curl_response->headers['Status-Code'] == "200") {
$content = json_decode($curl_response, true);
$response = array(
'status' => 'success',
'data' => array(
'pagespeed_score' => (int)$content['score'],
'pagespeed_stats' => $content['pageStats']
)
);
} else {
$response = array(
'status' => 'error',
'msg' => 'Google API Error. HTTP Code: ' . $curl_response->headers['Status-Code']
);
}
}
catch (Exception $e)
{
$response = array(
'status' => 'error',
'msg' => $e->getMessage()
);
}
return $response;
}
<?php
function checkPageSpeed($url){
if (function_exists('file_get_contents')) {
$result = #file_get_contents($url);
}
if ($result == '') {
$ch = curl_init();
$timeout = 60;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$result = curl_exec($ch);
curl_close($ch);
}
return $result;
}
$myKEY = "your_key";
$url = "http://kingsquote.com";
$url_req = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url='.$url.'&screenshot=true&key='.$myKEY;
$results = checkPageSpeed($url_req);
echo '<pre>';
print_r(json_decode($results,true));
echo '</pre>';
?>
The code shared by Siren Brown is absolutely correct, except that
while getting the scores we need to send the query parameter &strategy=mobile or &strategy=desktop to get the respective results from Page speed API
$url_mobile = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url='.$url.'&screenshot=true&key='.$myKEY.'&strategy=mobile';
$url_desktop = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url='.$url.'&screenshot=true&key='.$myKEY.'&strategy=desktop';
I have to fetch exam results from the page http://cbseresults.nic.in/class1211/cbse122012.htm
Sampleroll number is 4623447.
They are using http post to post the form data.I wrote the following code to post data.But it is not providing the needed results.I am posting the needed cookies and post variables.But still I am not getting the output.What change should I make for send_post function,so that it will be working.Here is my code
echo cbse12_data_extractor(4623447);
function cbse12_data_extractor($regNo) {
$source_url = 'http://cbseresults.nic.in/class1211/cbse122012.asp';
$post_vars = array('regno'=>$regNo);
$cookies = array('_tb_pingSent'=>1);
// $extraHeaders = array('Host'=>'http://cbseresults.nic.in');
return send_post($source_url,$post_vars,$cookies);
}
function send_post( $url, $data ,$cookies='',$extraHeaders = '') //sends data array(param=>val,...) to the page $url in post method and returns the reply string
{
$post = http_build_query( $data );
$header = "Accept-language: en\r\n".
"Content-Type: application/x-www-form-urlencoded\r\n" .
"Content-Length: " . strlen( $post ) .
"\r\nUser-agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)\r\n";
if($extraHeaders) {
foreach($extraHeaders as $headerN => $val) {
$header = $header.$headerN.': '.$val."\r\n";
}
}
if($cookies) {
$cookieArr = array();
foreach($cookies as $cookie => $value) {
array_push($cookieArr,$cookie.'='.$value);
}
$cookieStr = "Cookie: ".implode('; ',$cookieArr)."\r\n";
$header = $header.$cookieStr;
}
$context = stream_context_create( array(
"http" => array(
"method" => "POST",
"header" => $header,
"content" => $post
)
) );
//echo $header;
$page = file_get_contents( $url, false, $context );
return $page;
}
You can' send POST data using file_get_contents. Use CURL for this task
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,your_parameters);
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);