I am trying to use webhook to receieve data from a sms service provider.the hooked URL is http://exmple.com/xy/myphp.php and my myphp.php is as follows:
<?php
$con = new mysqli("server","uname","pass","db");
error_reporting(0);
$request = $_REQUEST["data"];
$jsonData = json_decode($request,true);
foreach($jsonData as $key => $value)
{
// request id
$requestID = $value['requestId'];
$userId = $value['userId'];
$senderId = $value['senderId'];
foreach($value['report'] as $key1 => $value1)
{
//detail description of report
$desc = $value1['desc'];
// status of each number
$status = $value1['status'];
// destination number
$receiver = $value1['number'];
//delivery report time
$date = $value1['date'];
$sql="INSERT INTO `delivary_report`(`request_id`, `user_id`, `sender_id`,`date`,`receiver`,`status`,`description`) VALUES('$requestID','$userId','$senderId','$date','$receiver','$status','$desc')";
$res=$con->query($sql);
}
}
//echo $request;
?>
the sms service provider is saying that they can get 406 error. please tell me how to solve this issue. currently i am using godaddy shared server. the json formated data they are sending looks like the follows.
data=[
{
"requestId":"35666a716868323535323239",
"userId":"38229",
"report":[
{
"desc":"REJECTED",
"status":"16",
"number":"91XXXXXXXXXX",
"date":"2015-06-10 17:09:32.0"
}
],
"senderId":"tester"
},
{
"requestId":"35666a716868323535323239",
"userId":"38229",
"report":[
{
"desc":"REJECTED",
"status":"16",
"number":"91XXXXXXXXXX",
"date":"2015-06-10 17:09:32.0"
},
{
"desc":"REJECTED",
"status":"16",
"number":"91XXXXXXXXXX",
"date":"2015-06-10 17:09:32.0"
}
],
"senderId":"tester"
}
]
Related
I'm using two API keys to receive the data. That's because provider have some daily quota limit. If quota exceeds the daily limit, 403 error is returned from the server.
I used $http_response_header to check the response from the server. But the problem is that when response returned isn't 200, e.g the API key used exceeds the daily limit, the code should execute again so that another API key is picked randomly. Here's the code I'm using:
$keys = array('1stkey','2ndkey');
$key_r = array_rand($keys);
$yt_key = $keys[$key_r];
$data = file_get_contents("https://example.com/data&key=$yt_key");
if (strpos($http_response_header[0], "200")) {
echo $data;
}
else{
echo 'No';
}
You can create a function of this code, and just re-run the function when the response is not 200. Something like this maybe?
function getAPIData() {
$keys = array('1stkey','2ndkey');
$key_r = array_rand($keys);
$yt_key = $keys[$key_r];
$data = file_get_contents("https://example.com/data&key=$yt_key");
if (strpos($http_response_header[0], "200")) {
echo $data;
}
else {
getAPIData();
}
}
Like #Jaquarh says, you might want to change max_execution_time also. Have a look here and see what works for you.
I've created perfect solution, check this:
$api = array('1st key','2nd key');
$k = array_rand($api);
$api_key_yt = $api[$k];
$total_api=count($api);
for ($loop=0;$loop<=$total_api;$loop++) {
$api_key_yt=$api[$loop];
$request2 = "https://example.com/?data&key=$api_key_yt";
$response = file_get_contents($request2);
$jsonobj = json_decode($response);
if (isset($jsonobj->items)) {break;} else {unset($jsonobj);}
}
print_r($jsonobj);
Please try this
$data = null;
do {
$keys = array('1stkey','2ndkey')
$key_r = array_rand($keys);
$yt_key = $keys[$key_r];
$data = file_get_contents("https://example.com/data&key=$yt_key");
} while ($data == null);
I'm setting up a chatbot (dialogflow) with a PHP webhook
What I want to do is to take the user input to query a MySQL table and pass the result back to the dialogflow API
So far I succeeded with passing a text string back to the API, but I don't understand how to query the database and pass the result back to the dialogflow API
I'll appreciate your help with this
I've used the API format from the dialogflow docs here
This is what I have
<?php
$method = $_SERVER['REQUEST_METHOD'];
if($method == 'POST') {
$requestBody = file_get_contents('php://input');
$json = json_decode($requestBody);
$text = $json->result->parameters->cities;
$conn = mysqli_connect("xxx", "xxx", "xxx", "xxx");
$sql = "SELECT * FROM exampletable LIKE '%".$_POST["cities"]."%'";
$result = mysqli_query($conn, $sql);
$emparray = array();
while($row =mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
$speech = $emparray;
$response->speech = $speech;
$response->displayText = $speech;
$response->source = "webhook";
echo json_encode(array($response,$emparray));
else
{
echo "Method not allowed";
}
?>
Thankyou
whenever the webhook gets triggered you need to listen to actions from JSON responses,
from the action made the switch case of actions
index.php
<?php
require 'get_enews.php';
function processMessage($input) {
$action = $input["result"]["action"];
switch($action){
case 'getNews':
$param = $input["result"]["parameters"]["number"];
getNews($param);
break;
default :
sendMessage(array(
"source" => "RMC",
"speech" => "I am not able to understand. what do you want ?",
"displayText" => "I am not able to understand. what do you want ?",
"contextOut" => array()
));
}
}
function sendMessage($parameters) {
header('Content-Type: application/json');
$data = str_replace('\/','/',json_encode($parameters));
echo $data;
}
$input = json_decode(file_get_contents('php://input'), true);
if (isset($input["result"]["action"])) {
processMessage($input);
}
?>
get_enews.php
<?php
function getNews($param){
require 'config.php';
$getNews="";
$Query="SELECT link FROM public.news WHERE year='$param'";
$Result=pg_query($con,$Query);
if(isset($Result) && !empty($Result) && pg_num_rows($Result) > 0){
$row=pg_fetch_assoc($Result);
$getNews= "Here is details that you require - Link: " . $row["link"];
$arr=array(
"source" => "RMC",
"speech" => $getNews,
"displayText" => $getNews,
);
sendMessage($arr);
}else{
$arr=array(
"source" => "RMC",
"speech" => "No year matched in database.",
"displayText" => "No year matched in database.",
);
sendMessage($arr);
}
}
?>
So when the action gets caught it will get executed and goes in the getNews($param); function here I am getting year as a response from the user in my case and I am executing the query in the database and giving back a response from the database.
I am trying to build a JSON response from my server side, but it is not working as expected.
It is probably something simple but, I am not so good at PHP...
The basic expected response is a JSON with a single JsonArray and some other fields, for that, the relevant piece of code is shown here:
Sample of expected JSON response:
{
"pageNr": 2
"totalPages":28
"products":[
{
"user_name":"testUser001",
"product_ID":"4756373abdhg"
},
{
"user_name":"testUser002",
"product_ID":"475ggdfghghg"
},
{
"user_name":"testUser003",
"product_ID":"47466gdgbdhg"
},
{
"user_name":"testUser004",
"product_ID":"4000nfaergeb"
},
{
"user_name":"testUser005",
"product_ID":"adfer73abdhg"
}
]
}
Basic PHP code used to generate desired JSON (among sql query and other things):
$res = array();
$res2 = array();
while($r = mysqli_fetch_assoc($query2)) {
$res["user_name"] = $r["user_name"];
$res["product_ID"] = $r["prod_ID"];
array_push($res2,$res);
}
$response = ['pageNr' => $page];
$response = ['totalPages' => $totalPages];
$response = ['products' => $res2];
Response that this code is generating on Postman:
{
"products":[
{
"user_name":"testUser001",
"product_ID":"4756373abdhg"
},
{
"user_name":"testUser002",
"product_ID":"475ggdfghghg"
},
{
"user_name":"testUser003",
"product_ID":"47466gdgbdhg"
},
{
"user_name":"testUser004",
"product_ID":"4000nfaergeb"
},
{
"user_name":"testUser005",
"product_ID":"adfer73abdhg"
}
]
}
So, for some reason the JSON response is not accepting more fields pageNrand totalPages.
What is wrong here?.
Each assignment overwrites your array. You need to update it instead:
$res = array();
$res2 = array();
while($r = mysqli_fetch_assoc($query2)) {
$res["user_name"] = $r["user_name"];
$res["product_ID"] = $r["prod_ID"];
array_push($res2,$res);
}
$response = [];
$response['pageNr'] = $page;
$response['totalPages'] = $totalPages;
$response['products'] = $res2;
Try;
$res = array();
$res2 = array();
while($r = mysqli_fetch_assoc($query2)) {
$res["user_name"] = $r["user_name"];
$res["product_ID"] = $r["prod_ID"];
array_push($res2,$res);
}
$response .= ['pageNr' => $page];
$response .= ['totalPages' => $totalPages];
$response .= ['products' => $res2];
I am pulling a report using the Adobe API from Omniture.
Here is the full script :
<?php
include_once('/path/SimpleRestClient.php');
// Date
$end_date = date("Y-m-d",strtotime("-1 days"));
$start_date = date("Y-m-d",strtotime("-8 days"));
// Location of the files exported
$adobe_file = '/path/Adobe_'.$end_date.'.csv';
// List creation that will be updated with the fields and be put into my CSV file
$list = array
(
array('lasttouchchannel', 'product','visits','CTR(Clicks/PageViews)') // headers // ADD or DELETE metrics #
);
function GetAPIData($method, $data)
{
$username = "XXXX";
$shared_secret = "XXXX";
$postURL = "https://api3.omniture.com/admin/1.4/rest/?method=";
// Nonce is a simple unique id to each call to prevent MITM attacks.
$nonce = md5(uniqid(php_uname('n'), true));
// The current timestamp in ISO-8601 format
$nonce_ts = date('c');
/* The Password digest is a concatenation of the nonce, it is timestamp and your password
(from the same location as your username) which runs through SHA1 and then through a base64 encoding */
$digest = base64_encode(sha1($nonce . $nonce_ts . $shared_secret));
$rc = new SimpleRestClient();
$rc -> setOption(CURLOPT_HTTPHEADER, array("X-WSSE: UsernameToken Username=\"$username\", PasswordDigest=\"$digest\", Nonce=\"$nonce\", Created=\"$nonce_ts\""));
//var_dump($o);
$rc -> postWebRequest($postURL .$method, $data);
return $rc;
}
$method = 'Report.Queue';
$data ='
{
"reportDescription":
{
"reportSuiteID":"XXXX",
"dateFrom":"'.$start_date.'",
"dateTo":"'.$end_date.'",
"metrics":[{"id":"visits"},{"id":"instances"},{"id":"pageviews"}],
"elements":[{"id":"lasttouchchannel","top":"50000"}]
}
}';
/*
"date":"'.$date.'",
"dateTo":"'.$date.'",
"dateFrom":"'.$start_date.'",
"dateTo":"'.$end_date.'",
*/
$rc=GetAPIData($method, $data);
if($rc -> getStatusCode() == 200) // status code 200 is for 'ok'
{
$counter = 0;
do
{
if($counter>0){sleep($sleep = 120);}
$return = GetAPIData('Report.Get', $rc->getWebResponse());
$counter++;
}while($return -> getStatusCode() == 400 && json_decode($return->getWebResponse())->error == 'report_not_ready'); // status code 400 is for 'bad request'
//
$json=json_decode($return->getWebResponse());
foreach ($json->report->data as $el)
{
echo $el->name.":".$el->counts[0].":".$el->counts[1]."\n";
// Adding the data in the CSV file without overwriting the previous data
array_push($list, array($el->name, $el->name, $el->counts[0], ($el->counts[1])/($el->counts[2])));
}
}
else
{
echo "Wrong";
}
$fp = fopen($adobe_file, 'w');
foreach ($list as $fields)
{
// Save the data into a CSV file
fputcsv($fp, $fields);
}
fclose($fp);
?>
How can I get the names of the metrics and elements in order to use them in this script? There is no way. I searched with all the possible tags on google and nothing worked !
I need the metrics and elements for this part of the code :
$data ='
{
"reportDescription":
{
"reportSuiteID":"XXXX",
"dateFrom":"'.$start_date.'",
"dateTo":"'.$end_date.'",
"metrics":[{"id":"visits"},{"id":"instances"},{"id":"pageviews"}],
"elements":[{"id":"lasttouchchannel","top":"50000"}]
}
}';
I cannot find 'date' as an element which is crucial. I cannot find all the other metrics as well. In Google Analytics we had this link :
Google Analytics Query
but in Adobe there is not any. I want something like that :
"metrics":[{"id":"instances"},{"id":"impressions"}],
"elements":[{"id":"date","top":"50000"}]
You would json_decode() as $data contains a JSON string. For example:
$data ='
{
"reportDescription":
{
"reportSuiteID":"XXXX",
"dateFrom":"'.$start_date.'",
"dateTo":"'.$end_date.'",
"metrics":[{"id":"visits"},{"id":"instances"},{"id":"pageviews"}],
"elements":[{"id":"lasttouchchannel","top":"50000"}]
}
}';
$json = json_decode($data, true);
echo $json['reportDescription']['dateFrom'];
print_r($json['reportDescription']['metrics']);
Am a trying to create a PHP (PHrets) script that downloads all real estate listing information from a specific area and saves all of the listings data (CSV file and photos) on my web server.
Note: A single listing may have up to 20 photos.
I am using PHrets to retrieve MLS listing data and it works great for creating a CSV of data. However, I would like to modify this code to loop through each listing's photos and download them onto my web server with the following name convention: MLSID-PHOTOID.
The error below is coming from the GetObject loop at the end of the code:
ERROR Message: HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request.
Thanks in advance!
<?php
$rets_login_url = "http://maxebrdi.rets.fnismls.com/Rets/FNISRETS.aspx/MAXEBRDI/login?&rets-version=rets/1.5";
$rets_username = "MyUser";
$rets_password = "MyPass";
// use http://retsmd.com to help determine the SystemName of the DateTime field which
// designates when a record was last modified
$rets_status_field = "L_StatusCatID";
$rets_city_field = "L_City";
// use http://retsmd.com to help determine the names of the classes you want to pull.
// these might be something like RE_1, RES, RESI, 1, etc.
//"RE_1"
$property_classes = array("LR_5");
// DateTime which is used to determine how far back to retrieve records.
// using a really old date so we can get everything
$listing_status = 1;
$listing_city = "OAKLAND";
//////////////////////////////
require_once("phrets.php");
// start rets connection
$rets = new phRETS;
echo "+ Connecting to {$rets_login_url} as {$rets_username}<br>\n";
$connect = $rets->Connect($rets_login_url, $rets_username, $rets_password);
if ($connect) {
echo " + Connected<br>\n";
}
else {
echo " + Not connected:<br>\n";
print_r($rets->Error());
exit;
}
foreach ($property_classes as $class) {
echo "+ Property:{$class}<br>\n";
$file_name = strtolower("property_{$class}.csv");
$fh = fopen($file_name, "w+");
$maxrows = true;
$offset = 1;
$limit = 1000;
$fields_order = array();
while ($maxrows) {
$query = "({$rets_status_field}={$listing_status}),({$rets_city_field}={$listing_city})";
// run RETS search
echo " + Query: {$query} Limit: {$limit} Offset: {$offset}<br>\n";
$search = $rets->SearchQuery("Property", $class, $query, array("Limit" => $limit, "Offset" => $offset, "Format" => "COMPACT", "Select" => "L_ListingID,L_Class,L_Type_,L_Status,L_AskingPrice,L_Keyword2,L_Keyword3,L_Keyword4,L_SquareFeet,L_Remarks,L_Address,L_City,L_State,LO1_OrganizationName,LA1_AgentLicenseID,LA1_UserFirstName,LA1_UserLastName,L_PictureCount", "Count" => 1));
if ($rets->NumRows() > 0) {
if ($offset == 1) {
// print filename headers as first line
$fields_order = $rets->SearchGetFields($search);
fputcsv($fh, $fields_order);
}
// process results
while ($record = $rets->FetchRow($search)) {
$this_record = array();
foreach ($fields_order as $fo) {
$this_record[] = $record[$fo];
}
fputcsv($fh, $this_record);
}
$offset = ($offset + $rets->NumRows());
}
$maxrows = $rets->IsMaxrowsReached();
echo " + Total found: {$rets->TotalRecordsFound()}<br>\n";
$rets->FreeResult($search);
}
fclose($fh);
echo " - done<br>\n";
}
/*
//This code needs to be fixed. Not sure how to include the listing array correctly.
$photos = $rets->GetObject("Property", "Photo", $record[ListingID], "*", 1);
foreach ($photos as $photo) {
$listing = $photo['Content-ID'];
$number = $photo['Object-ID'];
if ($photo['Success'] == true) {
echo "{$listing}'s #{$number} photo is at {$photo['Location']}\n";
file_put_contents("photos/{$photo['Content-ID']}-{$photo['Object-ID']}.jpg",
$photo['Data']);
}
else {
echo "Error ({$photo['Content-ID']}-{$photo['Object-ID']}
}
}
//ERROR Message: HTTP Error 500 (Internal Server Error): An unexpected condition was //encountered while the server was attempting to fulfill the request.
*/
echo "+ Disconnecting<br>\n";
$rets->Disconnect();
I modified your while loop that processes each record to also get the photos for that record. I also tested this on a RETS server.
while ($record = $rets->FetchRow($search)) {
$this_record = array();
foreach ($fields_order as $fo) {
if ($fo == 'L_ListingID') {
$photos = $rets->GetObject("Property", "Photo", $record[$fo], "*", 1);
foreach ($photos as $photo) {
if ($photo['Success'] == true) {
file_put_contents("photos/{$photo['Content-ID']}-{$photo['Object-ID']}.jpg", $photo['Data']);
}
}
}
$this_record[] = $record[$fo];
}
fputcsv($fh, $this_record);
}
One thing I found is you have ListingID on this line:
$photos = $rets->GetObject("Property", "Photo", $record[ListingID], "*", 1);
But then in your search query you refer to ListingID as L_ListingID. Maybe the above line should have L_ListingID.
$search = $rets->SearchQuery("Property", $class, $query, array("Limit" => $limit, "Offset" => $offset, "Format" => "COMPACT", "Select" => "L_ListingID,L_Class,L_Type_,L_Status,L_AskingPrice,L_Keyword2,L_Keyword3,L_Keyword4,L_SquareFeet,L_Remarks,L_Address,L_City,L_State,LO1_OrganizationName,LA1_AgentLicenseID,LA1_UserFirstName,LA1_UserLastName,L_PictureCount", "Count" => 1));
What if the last parameter of GetObject is "0" :
$photos = $rets->GetObject("Property", "Photo", $record[$fo], "*", 1);
in this case "1" is for retreiving the location. some servers this is switched off and return the actual image I believe - that would require a different method.