Showing results of query in dialogflow from php file - php

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"
)
)
],
),
));
}
?>

Related

How can i do this I want to store Views in mysql db in 1000=1k, 100000=100k, 1000000=1M and so on

I have php code below i want to do this I want to store Views in mysql db in 1000=1k, 100000=100k, 1000000=1M and so on so can any one please tell me how can i do this
function updateVideoView()
{
require_once("config.php");
$input = #file_get_contents("php://input");
$event_json = json_decode($input,true);
//print_r($event_json);
if(isset($event_json['id']))
{
$id=htmlspecialchars(strip_tags($event_json['id'] , ENT_QUOTES));
mysqli_query($conn,"update videos SET view =view+1 WHERE id ='".$id."' ");
$array_out[] =
array(
"response" =>"success");
$output=array( "code" => "200", "msg" => $array_out);
print_r(json_encode($output, true));
}
else
{
$array_out = array();
$array_out[] =
array(
"response" =>"Json Parem are missing");
$output=array( "code" => "201", "msg" => $array_out);
print_r(json_encode($output, true));
}
}

Fulfilment response PHP webhook not showing up in Actions on Google

The fulfilment response is visible in diagnostic info in the Dialogflow environment. But it's not showing up when I test it in Actions on Google. Anyone who knows how to let it work? Here is my webhook code:
<?php
$method = $_SERVER['REQUEST_METHOD'];
if($method == 'POST'){
$requestBody = file_get_contents('php://input');
$json = json_decode($requestBody);
$text = $json->queryResult->queryText;
$date = (!empty($json->queryResult->parameters->date)) ? $json->queryResult->parameters->date : '';
$environment = (!empty($json->queryResult->parameters->environment)) ? $json->queryResult->parameters->environment : '';
$intent = (!empty($json->queryResult->intent->displayName)) ? $json->queryResult->intent->displayName : '';
$responseText = prepareResponse($intent, $text, $date, $environment);
$response = new \stdClass();
$response->speech = $responseText;
$response->displayText = $responseText;
$response->source = "webhook";
header("Content-type:application/json");
echo json_encode($response);
}
else
{
echo "Method not allowed";
}
function prepareResponse($intent, $text, $date, $environment)
{
return "You said: " . $text . " | I found Intent: " . $intent . " | with parameters: date=" . $date . " environment=" . $environment;
}
?>
Responses for Actions on Google should be in an object under the payload attribute that contains a single attribute google with the AoG response format.
I haven't tested it, and this may not be the best way to build it, but something like the following should work:
$response->payload = array(
"google" => array(
"expectUserResponse" => TRUE,
"richResponse" => array(
"items" => array(
array(
"simpleResponse" => array(
"textToSpeech" => $responseText
)
)
)
)
)
);

504 Gateway time out 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?

PHP $get_ empty when data is posted from website, but not manual url

I have an odd problem with this script. I can post directly to it using the URL: "http://example.com/script.php?payer_email=foo&txn_id=9229fjfua822". But trying to post the same data from lets say http://requestmaker.com nothing is showing in the variable(s). I'm using nginx with PHP5.
<?php
$panel_url = 'http://example.com:23462/';
$username = $_GET['payer_email'];
$invoice = $_GET['txn_id'];
$trimmedinvoice = substr($invoice, -6);
$password = $trimmedinvoice;
$max_connections = 1;
$reseller = 0;
$bouquet_ids = array(
1,
2,
3 );
$expirationdays = $_GET['custom'];
$expiration = "+$expirationdays day";
$expiredate = strtotime($expiration);
###############################################################################
$post_data = array( 'user_data' => array(
'username' => $username,
'password' => $password,
'max_connections' => $max_connections,
'is_restreamer' => $reseller,
'exp_date' => $expiredate,
'bouquet' => json_encode( $bouquet_ids ) ) );
$opts = array( 'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query( $post_data ) ) );
$context = stream_context_create( $opts );
$api_result = json_decode( file_get_contents( $panel_url . "api.php?action=user&sub=create", false, $context ) );
Echo "<b>Username:</b> <br>";
echo $username;
echo "<br></br>";
echo "<b>Password:<br></b>";
echo $password;
echo "<br></br>";
echo "<b>Expires (in unix time):<br></b>";
echo $expiredate;
?>
Been testing all night and found that adding this code will return the data being passed without problems. So the problem seems to be with the script, not the setup itself. Just can't figure where I'm going wrong.
print "CONTENT_TYPE: " . $_SERVER['CONTENT_TYPE'] . "<BR />";
$data = file_get_contents('php://input');
print "DATA: <pre>";
var_dump($data);
var_dump($_POST);
print "</pre>";
Output from the last block of code posting directly with the URL:
CONTENT_TYPE:
DATA:
string(0) ""
array(0) {
}
Output from the last block of code posting using an external poster like the requestmaker:
CONTENT_TYPE:
text/html<BR />
DATA: <pre>string(35) "payer_email=foo&txn_id=9229fjfua822"
array(0) {
}
POST variables are in $_POST not $_GET (the latter contains the arguments appended to the URI).
You could use $_REQUEST which contains both POST and GET variables.
See this document for more.

File Writing using PHP

I am working on a project in my college which is about developing an online autograder website like that of hackerrank for my college. Now, for compiling codes, I am using the API provided by sphere engines. The API is returning the output as a string which then I store it into a file. Then, I use a previously defined output file to compare this file and check accordingly whether the code is right or wrong. Now the problem is for eg. if output is like below:
Hello World
Hello World
Hello World
The string is written in the file as Hello WorldHello WorldHwllo World. I am using PHP to write text to file.
Is there any way to write the string as it is to a file?
Any other alternative method will also be appreciated.
Thank You.
EDIT
for eg if the code:
#include<iotsream>
using namespace std;
int main()
{
int i;
for(i=0;i<3;i++)
{
cout<<"Hello World\n";
}
return 0;
}
The output of this code should be
Hello World
Hello World
Hello World
And when i am displaying the string which is stored in a PHP array $data['output'], it is getting displayed normally but when i am writing this string to a file, It is getting stored in a single line. I want to store the string as it is i.e. in different lines.
Due to this, this file if not equal to the template output file which contains the string Hello World in different lines.
EDIT
This is the PHP code for the file which will take the source code and input and send it to the compiler and receive it's output accordingly.
<?php
error_reporting(0);
include_once '../connection-script.php';
session_start();
$user = 'xxxxx';
$pass = 'xxxxx';
$code = '';
$input = '';
$run = true;
$private = false;
$subStatus = array(
0 => 'Success',
1 => 'Compiled',
3 => 'Running',
11 => 'Compilation Error',
12 => 'Runtime Error',
13 => 'Timelimit exceeded',
15 => 'Success',
17 => 'memory limit exceeded',
19 => 'illegal system call',
20 => 'internal error'
);
$error = array(
'status' => 'error',
'output' => 'Something went wrong :('
);
//echo json_encode( array( 'hi', 1 ) ); exit;
//print_r( $_POST ); exit;
if ( isset( $_POST['process'] ) && $_POST['process'] == 1 ) {
$lang = isset( $_POST['lang'] ) ? intval( $_POST['lang'] ) : 1;
$input = trim( $_POST['input'] );
$code = trim( $_POST['source'] );
$answerfile=$_POST['answerfile'];
$outputfile=$_POST['outputfile'];
$client = new SoapClient( "http://ideone.com/api/1/service.wsdl" );
//create new submission
$result = $client->createSubmission( $user, $pass, $code, $lang, $input, $run, $private );
//if submission is OK, get the status
if ( $result['error'] == 'OK' ) {
$status = $client->getSubmissionStatus( $user, $pass, $result['link'] );
if ( $status['error'] == 'OK' ) {
//check if the status is 0, otherwise getSubmissionStatus again
while ( $status['status'] != 0 ) {
sleep( 3 ); //sleep 3 seconds
$status = $client->getSubmissionStatus( $user, $pass, $result['link'] );
}
//finally get the submission results
$details = $client->getSubmissionDetails( $user, $pass, $result['link'], true, true, true, true, true );
if ( $details['error'] == 'OK' ) {
//print_r( $details );
if ( $details['status'] < 0 ) {
$status = 'waiting for compilation';
} else {
$status = $subStatus[$details['status']];
}
$data = array(
'status' => 'success',
'meta' => "Status: $status | Memory: {$details['memory']} | Returned value: {$details['status']} | Time: {$details['time']}s",
'output' => htmlspecialchars( $details['output'] ),
'raw' => $details
);
if( $details['cmpinfo'] ) {
$data['cmpinfo'] = $details['cmpinfo'];
}
$myfile=fopen("output.txt","w");
fwrite($myfile, $data['output']);
fclose($myfile);
$qid=$_POST['questionid'];
$did=$_POST['domainid'];
if(sha1_file("output.txt") == sha1_file($outputfile))
{
$file=fopen($answerfile,"w");
fwrite($file,$code);
fclose($file);
$mail=$_SESSION['email'];
$query="SELECT * from student where semail='$mail'";
$result1=mysql_query($query);
$row1=mysql_fetch_array($result1);
$sid=$row1['studentid'];
$sql="SELECT * from practiceques where did='$did' and quesid='$qid'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$marks=$row['marks'];
$curdate=date("Y-m-d H:i:s");
$answer=mysql_query("INSERT INTO points VALUES ('$sid','$qid','$curdate',1,'$marks','$did')");
echo json_encode( $data );
}
else
{
$mail=$_SESSION['email'];
$query="SELECT * from student where semail='$mail'";
$result1=mysql_query($query);
$row1=mysql_fetch_array($result1);
$sid=$row1['studentid'];
$sql="SELECT * from practiceques where did='$did' and quesid='$qid'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$marks=$row['marks'];
$curdate=date("Y-m-d H:i:s");
$answer=mysql_query("INSERT INTO points VALUES ('$sid','$qid','$curdate',0,0,'$did')");
echo json_encode($data);
}
}
else {
//we got some error :(
//print_r( $details );
echo json_encode( $error );
}
}
else {
//we got some error :(
//print_r( $status );
echo json_encode( $error );
}
} else {
//we got some error :(
//print_r( $result );
echo json_encode( $error );
}
}
?>
You can't write with C in php document.
Anyway, This is the php code for write in file.
<?php
$fp = fopen('file.name', 'a+');
fwrite($fp, 'Hello World'.PHP_EOL);
fclose($fp);
?>

Categories