Making http request from PHP file with JSON response - php

I am in the process of trying to call a php script over http and receive a json object back from where I plan to process further.
Basically, the code is as follows:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$version=$_GET["v"];
$product=$_GET["p"];
$stream=$_GET["s"];
$cmd=$_GET["c"];
$string = file_get_contents("http://localhost:82/releasenote/src/getTSBDetails.php?p=$product&v=$version&s=$stream&c=$cmd");
print_r($string);
exit();
} else {
print("2");
$string = file_get_contents('tsbDetails.json');
}
When the get_file_contents http request is called directly in the browser, the output is a json, but when trying using the above there is no response.

<?php
// JSon request format is :
// {"userName":"654321#zzzz.com","password":"12345","emailProvider":"zzzz"}
// read JSon input
$data_back = json_decode(file_get_contents('php://input'));
// set json string to php variables
$userName = $data_back->{"userName"};
$password = $data_back->{"password"};
$emailProvider = $data_back->{"emailProvider"};
// create json response
$responses = array();
for ($i = 0; $i < 10; $i++) {
$responses[] = array("name" => $i, "email" => $userName . " " . $password . " " . $emailProvider);
}
// JSon response format is :
// [{"name":"eeee","email":"eee#zzzzz.com"},
// {"name":"aaaa","email":"aaaaa#zzzzz.com"},{"name":"cccc","email":"bbb#zzzzz.com"}]
// set header as json![enter image description here][2]
header("Content-type: application/json");
// send response
echo json_encode($responses);
?>
[1]: http://i.stack.imgur.com/I7imt.jpg
[2]: http://i.stack.imgur.com/XgvOT.jpg

First of all you should make sure your variables can be used in the url:
$version=urlencode($_GET["v"]);
$product=urlencode($_GET["p"]);
$stream=urlencode($_GET["s"]);
$cmd=urlencode($_GET["c"]);
Then you should check if the value you read in $string is valid json. You can use this answer for that.
Then, if your string contains valid json, you should just echo it.
Finally, if you always expect json from your script, you should also json_encode your error handling:
} else {
echo json_encode("2");
// $string = file_get_contents('tsbDetails.json'); /* commented out as you don't seem to use it */
}

Related

Empty Response from a webhook using php

When a new record is created or updated, the Webhook is triggered and it posts three keys in the post body. One of the keys named payload contains encoded JSON with attributes of the record.
This is an example of the POST body message:See the Payload here
I want when the webhook fires it creates a file and posts the date to the file but I'm geting empty payload.
Here is the code.
<?php
/**
* Created by PhpStorm.
* User: Lee N
* Date: 16/07/2018
* Time: 14:46
*/
$data = file_get_contents('php://input');
//decode JSON data to PHP array
$content = json_decode($data, true);
if($content ==""){
$data = "Payload fired but no datkhkjhkjhjka";
}else{
$data = $content;
}
$pagename = 'from_vend';
$newFileName = $pagename.".txt";
if (file_put_contents($newFileName, $data) !== false) {
echo "File created (" . basename($newFileName) . ")";
} else {
echo "Cannot create file (" . basename($newFileName) . ")";
}
Your POST request is x-www-form-urlencoded. Quoting Wikipedia (emphasis mine):
When a web browser sends a POST request from a web form element, the default Internet media type is "application/x-www-form-urlencoded". This is a format for encoding key-value pairs with possibly duplicate keys. Each key-value pair is separated by an '&' character, and each key is separated from its value by an '=' character. Keys and values are both escaped by replacing spaces with the '+' character and then using URL encoding on all other non-alphanumeric[9] characters.
When you send a POST request like this to PHP, it will automatically populate $_POST with the key/value pairs. So in order to access the JSON payload, use
$decodedJson = json_decode($POST['payload']);
Whereas php://input is (quoting the PHP Manual):
a read-only stream that allows you to read raw data from the request body.
Since this is raw data (as in full post body), you would need to run it through parse_str first in order to decode the JSON payload (which is what PHP does automatically for you in $_POST).
If you want to write the full post body, you can just remove the json_decode. Because the full post body is not JSON and hence, will not decode as JSON.
Try using
parse_str($str, $output);
instead of
json_decode($data, true);
the post request is x-www-form-urlencoded. So json_decode will not work here as it is not a json string. If we check the payload we can see that it is a query string and parse_str will parse it into variables.
so the code will be
<?php
/**
* Created by PhpStorm.
* User: Lee N
* Date: 16/07/2018
* Time: 14:46
*/
$data = file_get_contents('php://input');
//decode JSON data to PHP array
//$content = json_decode($data, true);
parse_str($data, $content );
if($content ==""){
$data = "Payload fired but no datkhkjhkjhjka";
}else{
$data = $content;
}
$pagename = 'from_vend';
$newFileName = $pagename.".txt";
if (file_put_contents($newFileName, $data) !== false) {
echo "File created (" . basename($newFileName) . ")";
} else {
echo "Cannot create file (" . basename($newFileName) . ")";
}

Saving data across multiple lines JSON

Currently I have PHP and JS save my data in a JSON.
Below is the code for it:
PHP:
<?php
$jsonString = file_get_contents('passwords.json');
$data = json_decode($jsonString, true);
// get the q parameter from URL
$q = $_REQUEST["q"];
$item = $_REQUEST["item"];
// or if you want to change all entries with activity_code "1"
foreach ($data["passwords"] as $key => $password) {
echo $data["passwords"][$key]['timesToUse'] - 1;
if ($password['password'] == $q) {
$data["passwords"][$key]['timesToUse'] = $data["passwords"][$key]['timesToUse'] - 1;
$data["passwords"][$key]['winningItem'] = $item;
}
}
$newJsonString = json_encode($data);
file_put_contents('passwords.json', $newJsonString);
?>
JS:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "passwords.php?q="+passwords[i].password+"&item="+winningItem.getFullName(), true);
xmlhttp.send();
The issue that I am having is that initially my JSON file looks like this:
{"password":"IS360H","timesToUse":1,"winningItem":""},
{"password":"AGRD33","timesToUse":1,"winningItem":""},
{"password":"4BX0FV","timesToUse":1,"winningItem":""},
{"password":"99NOTX","timesToUse":1,"winningItem":""},
{"password":"X2Z8BO","timesToUse":1,"winningItem":""},
{"password":"R9G4Q0","timesToUse":1,"winningItem":""},
{"password":"CG9RGT","timesToUse":1,"winningItem":""},
As you can see it is nice and neat and is sitting at 1 password per line. However once the file gets modified, it turns to this:
{"password":"IS360H","timesToUse":0,"winningItem":"counterUAV"},{"password":"AGRD33","timesToUse":0,"winningItem":"sentryGun"},"password":"4BX0FV","timesToUse":0,"winningItem":"chopperGunner"},"password":"99NOTX","timesToUse":1,"winningItem":""},{"password":"X2Z8BO","timesToUse":1,"winningItem":""}, {"password":"R9G4Q0","timesToUse":1,"winningItem":""},"password":"CG9RGT","timesToUse":1,"winningItem":""},
What do I need to do to make my JSON file preserve the line breaks?
Thank you!
There is option JSON_PRETTY_PRINT available in json_encode function, if you are using same for encoding json. Try following:
$json_string = json_encode($data, JSON_PRETTY_PRINT);
Read more about json_encode

PHP script receives GET instead of POST REQUEST

I am using PHP with XAMPP and Dialogflow to create a chat interface. In a simple intent(question) in Dialogflow, I have created a webhook to XAMPP regarding the question 'Who is X' (e.g. Paul, George). Therefore , I place a POST REQUEST in order to have access to the json form of this question in DIalogflow so that I can answer it as I want to. Specifically, the ultimate goal of this is to retrieve some data from a MySQL database in phpMyAdmin about this question and respond for example that 'X is a developer' or 'X is a financial analyst'. This is why wrote a php script which is the following:
<?php
$method = $_SERVER['REQUEST_METHOD'];
// Process when it is POST method
if ($method == 'POST') {
$requestBody = file_get_contents('php://input');
$json = json_decode($requestBody);
$text = $json->result->parameters;
switch($text) {
case 'given-name':
$name = $text->given-name;
$speech = $name . 'is a developer';
break;
default:
$speech = 'Sorry I did not get this. Can you repeat please?';
}
$response = new \stdClass();
$response->speech = "";
$response->displayText = "";
$respone->source = "webhook";
echo json_encode($response);
}
else
{
echo "Method not allowed";
}
?>
However, the output of this program is: Method not allowed.
Paradoxically enough $method has the value 'GET' so it identifies a GET REQUEST while Dialogflow explicitly states at the webhook page that
Your web service will receive a POST request from Dialogflow in the
form of the response to a user query matched by intents with webhook
enabled.
Hence I am wondering: why my php script cannot see and process the POST REQUEST from Dialogflow?
P.S. Questions close to mine are the following: Form sends GET instead of POST, Why is $_SERVER['REQUEST_METHOD'] always GET?.
It doesn't work because $_SERVER['REQUEST_METHOD'] == "GET" by default.
So you program execute the 'else' condition.
You need to submit a request with the POST method to change this value.
You can use
<form method="POST">
[...]
</form>
in your HTML, or
$.ajax({
url : "ajax_url.php",
type : 'POST',
data : 'data='+data,
[...]
});
in your AJAX JS code for example
Here i am doing same like you from below code your Query will be resolved,
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);
}
}
?>
php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input

how to decode json data in php file

I want to decode json data which come from android like
["{\"User_Registartion_Details\":{\"fullname\":\"ssss\",\"emailid\":\"sumitbwm#gmail.com\",\"mobile\":\"8796485577\",\"location\":\"pune\"}}"]
how to do it....get data from json and save in my sql db suing php script trying but in my sql show null values. This my php code which get json data and decode then save in database.I tried but but store null values(blank).
Data get from android page in json format and decode in php script the save in db..anyboday have idea about this please help..i new in android/php.
This my php code which get json data and decode then save in database
<?php
// Include confi.php
include_once('conection.php');
if($_SERVER['REQUEST_METHOD'] == "POST" && $_SERVER["CONTENT_TYPE"] == "application/json")
{
$request = file_get_contents('php://input');
$array = json_decode($request,true);
$name = $array['fullname'];
$email = $array['emailid'] ;
$mobileno = $array['mobile'] ;
$location = $array['location'];
$sql = "INSERT INTO usertable (`fullname`, `emailid`, `mobile`, `location`) VALUES ('$array[name]', '$array[email]', '$array[mobileno]', '$array[location]')";
$qur = mysql_query($sql);
if($qur)
{
$json = array("status" => 1, "msg" => "Done User added!");
}
else
{
$json = array("status" => 0, "msg" => "Error adding user!");
}
}else
{
$json = array("status" => 0, "msg" => "Request method not accepted");
}
#mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
JSON Encoding and Decoding in PHP is done using the json_encode and `json_decode``functions.
// To encode
$encodes = json_encode($json);
// To decode
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
$decoded = json_decode($json);
// To see which variables are inside your decoded json
echo "<pre>";
var_dump($decoded);
echo "</pre>";
exit;
Edit
Your problem is that your json string is incorrect. I had to decode it twice to make it work.
// Incorrect json string
$json = '["{\"User_Registartion_Details\":{\"fullname\":\"ssss\",\"emailid\":\"sumitbwm#g‌​mail.com\",\"mobile\":\"8796485577\",\"location\":\"pune\"}}"]';
// Correct Json string
$json = '{"User_Registartion_Details":{"fullname":"ssss","emailid":"sumitbwm#g‌​mail.com","mobile":"8796485577","location":"pune"}}';
echo "<pre>";
var_dump(json_decode($json));
object(stdClass)#25 (1) {
["User_Registartion_Details"]=>
object(stdClass)#19 (4) {
["fullname"]=>
string(4) "ssss"
["emailid"]=>
string(24) "sumitbwm#g‌​mail.com"
["mobile"]=>
string(10) "8796485577"
["location"]=>
string(4) "pune"
}
}
You can access your request by looking at the $_POST variable
An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.
Display it using var_dump($_POST);
Example
// Your android application sends a request
// This request is part of the HTTP protocol
// It is either a POST, GET, PUT or DELETE request
// PHP handles PUT and DELETE as a POST request
// The request data will be stored in the $_POST varaible and the $_REQUEST variable
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Use a var_dump to learn what key holds the json data
var_dump($_POST);
// let's say its in $_POST['json']
$json = $_POST['json'];
var_dump(json_decode($json));
}
Resources
json_encode() - Manual
json_decode() - Manual

Get JSON object from URL Difficulties

I'm having difficulties grabbing any of the JSON information from this URL.
I've tried other JSON snippets and they seem to work so I'm not sure if it's the way that the URL is structured or something.
Basic example below.
<?php
$json = file_get_contents('http://nhs-sh.cfpreview.co.uk/api/version/fetchLatestData?dataType=Clinics&versionNumber=-1&uuID=website&dt=');
$obj = json_decode($json);
echo "Body: " . $obj->Body;
?>
The link provided starts with
{ data :
which is valid javascript but invalid json. You can test it on http://jsonlint.com. To fix this we can replace the data with "data" :
$json = file_get_contents('http://nhs-sh.cfpreview.co.uk/api/version/fetchLatestData?dataType=Clinics&versionNumber=-1&uuID=website&dt=');
$obj = json_decode($json);
if (json_last_error() !== JSON_ERROR_NONE) { //check if there was an error decoding json
$json = '{ "data" :'. substr(trim($json), 8); // replace the first 8-1 characters with { "data" :
$obj = json_decode($json);
}
print_r($obj->data); //show contents of data
Please note that this fix is dependent on the data source e.g. if they change data to dataset. The correct measure would be to ask the developers to fix their json implementation.

Categories