504 Gateway time out php - php

i'm running script(svc/rest services) that request a server which response me a XML string.. this request is going through an intermediate server.
My aim is to fetch the details of guests o.e. rooms which will be response..
but after certain number of request i am getting 504 gateway out and only about 40 rooms are able to retreived
1: file...source hots
$ROOMS = ["301","302","304","305","306","307","308","309","310",
"311","312","314","315","316","317","318","319","320",
"401","402","403","404","405","406","407","408","409",
"410","411","412","414","415","416","802","802","802",
"802","802","802","802","802","802","802","802","802",
"802","802","802","802","802","802","802","802","802",
"802","802","802","802","802","802","802","802"
];
// all rooms more than 75
for ($x = 0; $x < count($ROOMS); $x++){
$end_point = "https://www.innkeyapp.com/SerRest.svc/GetOccupiedRoomData";
$sharedkey = "2diSq8bjZ4N3ZR4XB5KXXXXXXXXXXXXXXXXXXXXXXX";
$url = 'https://eastern-services.com/innkeyPMS_room_ststus.php';
$room_no = $ROOMS[$x];
$postdata = http_build_query([
'end_point' => $end_point,
'room_no' => $room_no,
'sharedkey' => $sharedkey
]);
$opts = [
'http' => [
'method' => 'POST',
'content' => $postdata
]
];
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
$arrayData = json_decode($result,true);
if (empty($arrayData)) {
// Redirect('failure.php?msg=Error in service');
echo "Error in Service";
exit();
}
print_r($arrayData);
echo $room_no."Added";
}
2: file.... innkeyPMS_room_ststus.php i.e. intermediate host.
$room_no = $post_var['room_no'];
$end_point = $post_var['end_point'];
$sharedkey = $post_var['sharedkey'];
$registerno = '';
$prprtxt = '';
$validunit = '';
// echo $post_var;
function curl_get_file_contents($URL)
{
return file_get_contents($URL);
}
$xmlString = curl_get_file_contents(
$end_point.'sharedkey='.$sharedkey.'=&roomno='.$room_no
);
$xml = simplexml_load_string($xmlString);
header("Content-Type: application/json");
echo json_encode($xml);
why this connection is getting lost or why its showing 504 gateway time out?

Related

Showing results of query in dialogflow from php file

so I am creating a chatbot using dialogflow. I am writing my code in a php file and I am trying to get data from my database. The connection to the database works and the query returns results that I put in a varialbe called $ppp.I echo my results using a sendMessage function that I defined.The only problem is that I am only able to echo first result of the request it seems like the while loop isn't working or maybe there's a problem with the sendMessage function I don't know what to do.
<?php
header('Content-Type: text/html; charset=utf-8');
date_default_timezone_set("Asia/Bangkok");
$date = date("Y-m-d");
$time = date("H:i:s");
$json = file_get_contents('php://input');
$request = json_decode($json, true);
$input = fopen("log_json.txt", "w") or die("Unable to open file!");
fwrite($input,$json);
fclose($input);
function processMessage($update) {
if($update["queryResult"]["action"] == "ques"){
$bdd= new PDO('mysql:host=localhost;dbname=*****', '*****', '*****', array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")) ;
$nom= $update["queryResult"]["parameters"]["nom_aliment"];
$info=$update["queryResult"]["parameters"]["Information"];
$quantite=$update["queryResult"]["parameters"]["Quantite"];
$req=$bdd->query("SELECT * FROM TableCiqual");
$req=$bdd->prepare("SELECT * FROM TableCiqual WHERE alim_nom LIKE ? ");
$req->execute(array("%$nom%"));
while($resultat=$req->fetch()){
$variab=$resultat[$info]*$quantite/100;
$ppp =$resultat['alim_nom'].' '.$info.' : '.$variab;
sendMessage(array(
"source" => $update["responseId"],
"fulfillmentText"=>$ppp,
"payload" => array(
"items"=>[
array(
"simpleResponse"=>
array(
"textToSpeech"=>"Bad request"
)
)
],
),
));
//}
}
}
function sendMessage($parameters) {
echo json_encode($parameters);
}
$update_response = file_get_contents("php://input");
$update = json_decode($update_response, true);
if (isset($update["queryResult"]["action"])) {
processMessage($update);
}else{
sendMessage(array(
"source" => $update["responseId"],
"fulfillmentText"=>"Hello from webhook",
"payload" => array(
"items"=>[
array(
"simpleResponse"=>
array(
"textToSpeech"=>"Bad request"
)
)
],
),
));
}
?>

Telegram bot Inline keyboards sends too many callbacks PHP

So problem is I am using inline keyboard in my bot. And when I am trying to push this keyboard it gives me 3-5 callbacks. I don't know where is my mistake.
EDIT
I don't know why but it causes this error when i working with mysqli->fetch_assoc();
There is not full code just peace where I use inline keyboard
if ($callback_data!=Null){
checkJSON(3124,$order_id);
$message_id = $update['callback_query']['message']['message_id'];
$callback_data = json_decode($callback_data,true);
checkJSON(3125,$callback_data["order_id"]);
$order_id = $callback_data["order_id"];
checkJSON(3126,$order_id);
$rs = $mysqli->query("SELECT manager_id FROM orders WHERE id=".$order_id);
$row = $rs->fetch_assoc();
$manager = $row['manager_id'];
if ($manager!=Null){
$rs = $mysqli->query("SELECT telegram_id FROM managers WHERE id=".$manager);
$row = $rs->fetch_assoc();
$manager_telegram_id = $row['telegram_id'];
if ($chatID==$manager_telegram_id){
$callback_data = json_decode($callback_data);
$order_id = $callback_data["order_id"];
$status = $callback_data["status"];
checkJSON(1231234,$callback_data);
if($status == '3'){
editMessage($chatID,$message_id,"Заказ N".$order_id." подтвержден");
}
else{
editMessage($chatID,$message_id,"Заказ N".$order_id." отклонен");
}
$mysqli->query("UPDATE orders SET status=".$status." WHERE id=".$order_id);
}
sendMessage($chatID,$update['callback_query']['message']['message_id']);
editMessage($chatID,$message_id,
"Данный заказ уже в оброботке");
}
else{
$get_manager_query = $mysqli->query("SELECT id FROM managers WHERE telegram_id=".$chatID);
$row = $get_manager_query->fetch_assoc();
$manager = $row['id'];
$data1 = json_encode(array("order_id"=>$order_id,"status"=>3));
$data2 = json_encode(array("order_id"=>$order_id,"status"=>4));
$inline_button1 = array("text"=>"Принять","callback_data"=>$data1);
$inline_button2 = array("text"=>"Отказать","callback_data"=>$data2);
$inline_keyboard = [[$inline_button1,$inline_button2]];
$keyboard=json_encode(array("inline_keyboard"=>$inline_keyboard));
editMessage($chatID,$message_id,
"Вы приняли данный заказ",$keyboard);
$rs = $mysqli->query("UPDATE orders SET status=1, manager_id=".$manager." WHERE id=".$order_id);
}
}
function sendMessage($chatID,$text){
$sendto =API_URL."sendmessage?chat_id=".$chatID."&text=".urlencode($text);
file_get_contents($sendto);
}
function editMessage($chatId, $messageId, $message,$replyMarkup=Null) {
$url = API_URL."editMessageText?chat_id=".$chatId."&message_id=".$messageId.
"&text=".urlencode($message)."&reply_markup=".$replyMarkup;
file_get_contents($url);
}
It's Not your mistake!
Telegram Server is send callbacks for every changes in inline query.
You can setting that to off in BotFatherwith /setinlinefeedback command.
For more information visit this
Set your data by some separator After, get that data by $update['callback_query']['data'] and split by seted separator.
$botToken = "(your token)";
$website = "https://(site_url)/bot" . $botToken;
$order_id = '44423'; //my additional data
$keyboard = ["inline_keyboard" => [
[
[
"text" => "Доставлено",
"callback_data" => "delivered_".$order_id, // set few data by '_' separator Like ("delivered_443423_phone12345667_...)
],
[
"text" => "Затримуюсь",
"callback_data" => "delaying_".$order_id,
]
],
]
];
$params = [
'chat_id' => $chat_id,
'text' => $msg,
'parse_mode' => 'html',
'reply_markup' => json_encode($keyboard),
];
$ch = curl_init($website . '/sendMessage');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
Update processing. For get update you need set webhook on file where bot is placed. https://api.telegram.org/bot(your token)/setWebhook?url=https://example.com/bot_directory/bot.php Site must have SSL (https).
$update = json_decode(file_get_contents('php://input'), TRUE);
$botToken = "(your token)";
$botAPI = "https://api.telegram.org/bot" . $botToken;
$msg = $update['message']['text'];
$user_id = $update['message']['from']['id'];
if (isset($update['callback_query'])) {
$update_multiple = explode('_', $update['callback_query']['data']); //split data
if ($update_multiple[0] == 'delivered') {
$data1 = $update_multiple[1]; // get some data
// ......
}
}

Usaepay payment declines, ssl version error

I am using usaEpay for my mobile app. I was using my friend's server and there was no problem.
Then I rented a server for my own. switched the backend to the new server. I am using the exact same code. I implemented rapid SSL to my site. But I cannot make a payment.
This is the error;
Error reading from card processing gateway.
Unsupported SSL protocol version
My php api is the same as this; https://github.com/usaepay/usaepay-php/blob/master/usaepay.php
this is my payOrder.php class
require('connector.php');
include ('phpseclib/Crypt/RSA.php');
include ('usaepay/usaepay.php');
$request = json_decode($HTTP_RAW_POST_DATA, true);
$token = $request['token'];
$orderid = $request['orderid'];
$ccInfo = base64_decode($request['ccinfo']);
$address = $request['address'];
if(strlen($out_plain) >= 25) {
$query = "SELECT * FROM xxxx_order WHERE order_id = $orderid";
$result = mysql_query($query);
$order = mysql_fetch_assoc($result);
$total = $order['order_total'];
$creditcard = explode("||", $out_plain);
$ccnumber = $creditcard[0];
$cvvnumber = $creditcard[1];
$cctype = $creditcard[2];
$ccmonth = $creditcard[3];
$ccyear = $creditcard[4];
$ccdate = $ccmonth.$ccyear;
$ccname = $creditcard[5];
$address = explode("||", $address);
$street = $address[0];
$city = $address[1];
$state = $address[2];
$zip = $address[3];
$name = $address[4];
$umcommand = "cc:sale" ;
$umkey = "mykey" ;
$pin = "mypin";
$tran=new umTransaction;
$tran->key = "mytrkey";
$tran->pin = "mypin";
$tran->usesandbox = false;
$tran->testmode = 0;
$tran->command = "cc:sale";
$tran->card = $ccnumber;
$tran->exp = $ccdate;
$tran->amount = $total;
$tran->invoice = $orderid;
$tran->cardholder = $ccname;
$tran->street = $street;
$tran->zip = $zip;
$tran->description = "App sale";
$tran->cvv2 = $cvvnumber;
flush();
if($tran->Process()) {
$auth = $tran->authcode;
$refnum = $tran->refnum;
$response = "$auth---$refnum";
$query = "UPDATE `mydb` SET `order_status`= 2, UMresponse =
$check = false;
$count = 0;
do {
$check = mysql_query($query);
$count++;
} while ($check == false && $count < 50);
array_push($arr, array("status" => "success", "request" => "check", "order_status" => "success"));
} else {
$tranresult = $tran->result;
$tranerror = $tran->error;
$trancurl = "";
if(#$tran->curlerror) $trancurl = $tran->curlerror;
$response = "$tranresult---$tranerror---$trancurl";
$query = "UPDATE `mydb` SET `order_status`= 4, UMresponse = '$response' WHERE order_id = $orderid";
$check = false;
$count = 0;
do {
$check = mysql_query($query);
$count++;
} while ($check == false && $count < 50);
array_push($arr, array("status" => "success", "request" => "check", "order_status" => "declined"));
}
/*
$hashseed = mktime (); // mktime returns the current time in seconds since epoch.
$hashdata = $umcommand . ":" . $pin . ":" . $total . ":" . $orderid . ":" . $hashseed ;
$hash = md5 ( $hashdata );
$umhash = "m/$hashseed/$hash/y";
$fields = array(`enter code here`
"UMkey" => urlencode($umkey),
"UMredir" => urlencode("myurl"),
"UMinvoice" => urlencode($orderid),
"UMamount" => urlencode($total),
"UMname" => urlencode($ccname),
"UMstreet" => urlencode($street),
"city" => urlencode($city),
"City" => urlencode($city),
"state" => urlencode($state),
"State" => urlencode($state),
"UMzip" => urlencode($zip),
"cardtype" => urlencode($cctype),
"UMcard" => urlencode($ccnumber),
"UMexpir" => urlencode($ccdate),
"UMcommand" => urlencode("cc:sale"),
"UMhash" => $umhash,
"UMechofields" => "yes",
"OrderRef" => $orderid
);
$fields_string = "";
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
$url = "https://www.usaepay.com/gate.php";
// $fields = "UMkey=".urlencode($umkey)."&UMredir=".urlencode("myurl**strong text**")."&UMinvoice=$orderid&UMamount=".urlencode($total)."&UMname=".urlencode($ccname)."&UMstreet=".urlencode($street)."&city=".urlencode($city)."&state=".urlencode($state)."&UMzip=".urlencode($zip)."&cardtype=".urlencode($cctype)."&UMcard=".urlencode($ccnumber)."&UMexpir=".urlencode($ccdate)."&UMcommand=".urlencode("cc:sale");
// array_push($arr, array("url" => $url, "fields" => $fields_string));
//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, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
if($result == true) {
array_push($arr, array("status" => "success", "request" => "send", "msg" => "Payment request sent"));
}
else {
array_push($arr, array("status" => "error", "request" => "send", "msg" => "Failed to connect to the payment system"));
}
//close connection
curl_close($ch);
*/
} else {
array_push($arr, array("status" => "error", "request" => "send", "msg" => "Decryption failure, please check fields before submission"));
} else {
array_push($arr, array("status" => "error", "request" => "send", "msg" => "User token not verified"));
}
header('Content-Type: application/json');
echo json_encode($arr);
Any help would be overly appreciated. What is my problem ?
I think the error message said it clearly that your communication with payment gateway is rejected or refused due to unsupported SSL version, you should check your server setting and compare with your friend's server. BTW, looking at your PHP code, do you know that mysql extension has been deprecated since PHP v5.5.0 and total removed from PHP 7? I'd suggest that you read PHP The right way about the Database part and the php.net documentation.

Cache data server side for ajax request

I'm using TwitterAPIExchange and Instagram-PHP-API to request data from both APIs on my server, concatenate them into an array and build this into JSON which I can consume on the client with a simple GET request in jQuery.
This is all working fine, however it is quite slow. When I make a request to static JSON data as a test, it is far quicker. It seems the php script on my server to get this data is running each time (so starting with an empty array, using the wrappers the libraries provide to make requests etc.). What I would like to do is to cache/store this data, and only make another request once or twice a day.
My PHP knowledge is not the best so I'm sure there is a relatively simple way of doing this.
Here is the php script on my server:
<?php
header('Content-type:application/json;charset=utf-8');
require_once('TwitterAPIExchange.php');
require_once('Instagram.php');
unset($allFeeds);
$allFeeds = array();
$settings = array(
'oauth_access_token' => "XXXX' => "XXXX",
'consumer_key' => "XXXX",
'consumer_secret' => "XXXX"
);
$url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
$getfield = '?screen_name=XXX';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$twitter_response = $twitter->setGetfield($getfield)->buildOauth($url,$requestMethod)->performRequest();
$jsonTweets = json_decode($twitter_response);
foreach ($jsonTweets as $tweet) {
$tweetObj = new stdClass();
$tweetObj->type = 'Twitter';
$tweetObj->created_at = strtotime($tweet->created_at);
$tweetObj->text = $tweet->text;
$allFeeds[] = $tweetObj;
}
use MetzWeb\Instagram\Instagram;
$instagram = new Instagram(array(
'apiKey' => 'XXXX',
'apiSecret' => 'XXXX',
'apiCallback' => 'XXXX'
));
$token = 'XXX';
$code = $token;
$instagram->setAccessToken($code);
$id_one = 'XXX';
$id_two = 'XXX';
$insta_response_one = $instagram->getUserMedia($id_one, 20);
$insta_response_two = $instagram->getUserMedia($id_two, 10);
foreach ($insta_response_one->data as $insta_one) {
$instaObjOne = new stdClass();
$instaObjOne->type = 'Instagram One';
$instaObjOne->created_at = (int)$insta_one->created_time;
if (isset($insta_one->caption->text)) {
$instaObjOne->text = $insta_one->caption->text;
}
$instaObjOne->img = $insta_one->images->standard_resolution->url;
$allFeeds[] = $instaObjOne;
}
foreach ($insta_response_two->data as $insta_two) {
$instaObjTwo = new stdClass();
$instaObjTwo->type = 'Instagram Two';
$instaObjTwo->created_at = (int)$insta_two->created_time;
if (isset($insta_two->caption->text)) {
$instaObjTwo->text = $insta_two->caption->text;
}
$instaObjTwo->img = $insta_two->images->standard_resolution->url;
$allFeeds[] = $instaObjTwo;
}
function dateSort($a, $b) {
return $b->created_at - $a->created_at;
}
usort($allFeeds, "dateSort");
$data = json_encode($allFeeds);
// cache $data here?
echo $data;
?>
I bringing it into my frontend like so:
$.ajax({
type: 'GET',
url: 'path/to/script.php'
dataType: 'json',
}).done(function(data) {
// do stuff with data here
});
}
Hope that makes sense, thanks
This is the simplest way to add caching to your code.
It's using file_put_contents('cache.txt',$data) to cache the request data and then at the top of the file it checks the current time and compares with the last time the file was modified. If it was modified less than 24 hours ago, it just outputs the content of the cache file using echo file_get_contents('cache.txt); and stops the script.
<?php
header('Content-type:application/json;charset=utf-8');
// Check if file was modified less than 24 hours ago
if ((time() - filemtime('cache.txt')) < 24 * 60 * 60) {
// Output contents of cache file and stop script
echo file_get_contents('cache.txt');
exit();
}
require_once('TwitterAPIExchange.php');
require_once('Instagram.php');
unset($allFeeds);
$allFeeds = array();
$settings = array(
'oauth_access_token' => "XXXX" => "XXXX",
'consumer_key' => "XXXX",
'consumer_secret' => "XXXX"
);
$url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
$getfield = '?screen_name=XXX';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$twitter_response = $twitter->setGetfield($getfield)->buildOauth($url,$requestMethod)->performRequest();
$jsonTweets = json_decode($twitter_response);
foreach ($jsonTweets as $tweet) {
$tweetObj = new stdClass();
$tweetObj->type = 'Twitter';
$tweetObj->created_at = strtotime($tweet->created_at);
$tweetObj->text = $tweet->text;
$allFeeds[] = $tweetObj;
}
use MetzWeb\Instagram\Instagram;
$instagram = new Instagram(array(
'apiKey' => 'XXXX',
'apiSecret' => 'XXXX',
'apiCallback' => 'XXXX'
));
$token = 'XXX';
$code = $token;
$instagram->setAccessToken($code);
$id_one = 'XXX';
$id_two = 'XXX';
$insta_response_one = $instagram->getUserMedia($id_one, 20);
$insta_response_two = $instagram->getUserMedia($id_two, 10);
foreach ($insta_response_one->data as $insta_one) {
$instaObjOne = new stdClass();
$instaObjOne->type = 'Instagram One';
$instaObjOne->created_at = (int)$insta_one->created_time;
if (isset($insta_one->caption->text)) {
$instaObjOne->text = $insta_one->caption->text;
}
$instaObjOne->img = $insta_one->images->standard_resolution->url;
$allFeeds[] = $instaObjOne;
}
foreach ($insta_response_two->data as $insta_two) {
$instaObjTwo = new stdClass();
$instaObjTwo->type = 'Instagram Two';
$instaObjTwo->created_at = (int)$insta_two->created_time;
if (isset($insta_two->caption->text)) {
$instaObjTwo->text = $insta_two->caption->text;
}
$instaObjTwo->img = $insta_two->images->standard_resolution->url;
$allFeeds[] = $instaObjTwo;
}
function dateSort($a, $b) {
return $b->created_at - $a->created_at;
}
usort($allFeeds, "dateSort");
$data = json_encode($allFeeds);
// Cache $data here
file_put_contents('cache.txt', $data);
echo $data;
?>

How to add page links for multiple pages in Bing search api in php

I used the following code to include bing API in my web page. How can I add paging to this web search ?
Currently it shows only 1st 50 results and does not show the page links to other results. Also, how do I limit the results in one page to 20 ?
<?php
if (isset($_POST['submit']))
{
$acctKey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$rootUri = 'https://api.datamarket.azure.com/Bing/Search';
$query = $_POST['searchText'];
$serviceOp ='Web';
$market ='en-us';
$query = urlencode("'$query'");
$requestUri = "$rootUri/$serviceOp?\$format=json&Query=$query";
$auth = base64_encode("$acctKey:$acctKey");
$data = array(
'http' => array(
'request_fulluri' => true,
'ignore_errors' => true,
'header' => "Authorization: Basic $auth"
)
);
$context = stream_context_create($data);
$response = file_get_contents($requestUri, 0, $context);
$response=json_decode($response);
echo "<pre>";
echo("<ol>");
foreach($response->d->results as $value)
{
$Ur = $value->Url;
echo '<li class="resultlistitem"><a href="{$Ur}"> '.$Ur. '
</a><br><p>';
echo($value->Description .'</li> </p>');
}
echo("</ol>");
echo "</pre>";
}
?>

Categories