How to Pass values in web services - php

I have created a sample web services, This will return me a Json Data. looks like below.
http://127.0.0.1/Webservices/Oraconnect.php
<?php
header('Content-type: application/json');
$something = array();
array_push($something, array('say' => 'omg', 'dsay' => 'D omg'));
array_push($something, array('say' => 'bla', 'dsay' => 'D bla'));
$cont = array('result'=>$something);
$jsonresult = json_encode($cont);
print_r($jsonresult);
?>
Result:
{
result: [
{
say: "omg",
dsay: "D omg",
},{
say: "bla",
dsay: "D bla",
},
]
}
Now I want validated with UserName, which should take Value and change response accordingly.
something like this.
http://127.0.0.1/Webservices/Oraconnect.php?user=john
How can I add this validation and Change the response accordingly. Appreciate your help, thanks.

you could do something like that
<?php
header('Content-type: application/json');
if($_GET["user"])
{
$user = $_GET["user"];
// write your code that will use the user name
}
else
{
// return error or anything said the user is missing
}
?>

Related

PHP insert json object without main key

I am struggled at this point.
I am using the script for inserting/updating website languages.
The main structure of the JSON file looks like this
{
"English": {
"shortcode": "EN"
}
}
Here is a sample of the code I am using to insert a language into my JSON file
$data['french'] = $_POST;
array_push($json, $data);
$jsonData = json_encode($json, JSON_PRETTY_PRINT);
file_put_contents(__DIR__.'/../files/lg.json', $jsonData);
But when I insert a new record into my JSON file new key appends in my JSON file and it looks like this,
{
"English": {
"shortcode": "EN"
},
"0": {
"French": {
"shortcode": "FR"
}
}
}
So my question is how can I insert a new record but to not insert the key "0", "1"..
Thanks in advance.
You only have to make $json[key] = value
$json['French'] = $_POST;
If it does not exist it is added, otherwise it is updated
It seems the $_POST is an array.
So you are pushing an array onto the $json array
Try this:
$json = $json + $_POST;
$jsonData = json_encode($json, JSON_PRETTY_PRINT);
file_put_contents(__DIR__.'/../files/lg.json', $jsonData);

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

Struggling with a small json and php to get IP

PHP
<?php
header('Content-type: application/json');
$return['ip'] = $_SERVER['REMOTE_ADDR'];
$results[] = array(
'ip' => $return['ip']
);
echo json_encode($results);
?>
jQuery
$.getJSON("http://domain.com/json/",
function(data){
console.log(data.ip);
});
});
But when I run the jQuery I've checked Fire bug and it says the following
GET http://domain.com/json/ 200 OK 81ms
And doesn't respond with the IP that I requested for. Have I missed something?
UPDATED CODE
PHP
<?php
header('Content-type: application/json');
$return['ip'] = $_SERVER['REMOTE_ADDR'];
$results = array(
'ip' => $return['ip']
);
echo json_encode($results);
?>
jQuery
$.getJSON("http://domain.com/json/", function(data){
console.log(data.ip);
});
Firebug Error
SyntaxError: invalid label {"ip":"XXX.XXX.XXX.X"}
An arrow points at the first quotation mark just before the word ip.
You are returning:
[{'ip': 'XXX.XXX.XXX.XXX'}]
But you are treating it as if you are returning:
{'ip': 'XXX.XXX.XXX.XXX'}
You either need to change your JavaScript to console.log(data[0].ip) or change your PHP to: $results = array( ... ); rather than $results[] = array( ... );
Either will fix your problem. :)

php json format

I have a json response in this url, which I have to validate from this site.
I have stuck my head through many solutions,and I don't know what's wrong here.
I am very thankful for any help suggestions.
this is the code
header('Content-type: application/json');
$obj=array();
$UID=isset($_REQUEST['UID'])?$_REQUEST['UID']:'';
if($UID!='')
{
$sound_cloud=getLatestSound($UID);
if($sound_cloud==false)
{
$sound_cloud['status']="No Record Found";
$obj['status']="No Record Found";
}
else
{
$sound_cloud['status']="successfull";
}
}
else
{
$sound_cloud['errors']="required UID";
}
print stripslashes(json_encode($sound_cloud));
exit;
<?php
$json = '{"stream_url":"http://api.soundcloud.com/tracks/74950626/stream?client_id=b45b1aa10f1ac2941910a7f0d10f8e28","title":"Klaypex-Jump","status":"successfull"}';
$arrayval = json_decode($json);
print_r($arrayval);
// OR
$url = 'http://knowyourdj.staging.techliance.com/webservices?action=GetSoundCloud&UID=1';
$json = file_get_contents($url);
$arrayval = json_decode($json);
print_r($arrayval);
?>
Result:
stdClass Object ( [stream_url] => http://api.soundcloud.com/tracks/74950626/stream?client_id=b45b1aa10f1ac2941910a7f0d10f8e28 [title] => Klaypex-Jump [status] => successfull )
use
$json = file_get_contents('http://knowyourdj.staging.techliance.com/webservices?action=GetSoundCloud&UID=1');//fetch contents from server
$json = json_decode($json); // parse fetched contents
if(!empty($josn)){
print_r($json);
}else{
echo 'no result were found';
}
//lets find what we had parse
echo it, not print. just try~
print stripslashes(json_encode($sound_cloud));
=>
echo stripslashes(json_encode($sound_cloud));
------------------ edit
If this isn't a solution, I think this is a kind of same origin policy problem.
double check your url, it should have same domain with web page server.
refrence - same origin policy
use jquery jsonp,
You can make an ajax call with jquery to your php like this
$.ajax({
type:"POST",
url:'/example.php', //your url
data:{'seguros':a, 'esp':esp,'cont':cont}, //your variables
success: function(data){
//handle your answer here
}
});

PHP Use regex to find and remove a variable in a string

With PHP, I'm opening a file and it looks like this:
var people = {
vikram: { time1: [ '8:00am', '8:20am', '8:40am', '9:00am', ], time2: [ '10:20am', '10:40am', '11:00am', '11:20am', ], time3: [ '8:00am', '8:20am', '8:40am', ], }};
The variable I'm trying to remove will contain a time (ex. 8:00am) and I will know the timeIndex(ex. time1). I also want to keep all the other times intact.
For example, if I set the variable to 8:40am, I want the new file that is being created to look like this:
var people = {
vikram: { time1: [ '8:00am', '8:20am', '9:00am', ], time2: [ '10:20am', '10:40am', '11:00am', '11:20am', ], time3: [ '8:00am', '8:20am', '8:40am', ], }};
Any help would be appreciated!
The format you show represents a JSON formatted string. You can use json_decode() function to make an array from string, then loop through the array and just unset() the element you don't need.
you can use preg_replace() for this:
<?php
$filename = 'yourfile.js';
$search = '8:40am';
$content = file_get_contents( $filename );
$pattern = '/(\s*time1:\s*\[.*)([\'"]' .
preg_quote($search) .
'[\'"],?\s*)(.*\])/U';
$content = preg_replace( $pattern, '\1\3', $content );
file_put_contents( $filename, $content );
?>
This is a modification of the code example i answered to your last question on a similar topic.
Here is the way I did it. Basically, I use json_decode to parse your json to php object. However, I also found that your input is not a well-formed json for php (See example 3). Although my code doesn't look good and generic, but I hope it will help you.
<?php
$json_data = '{
"vikram": {
"time1": ["8:00am", "8:20am", "8:40am", "9:00am"],
"time2": ["10:20am", "10:40am", "11:00am", "11:20am"],
"time3": ["8:00am", "8:20am", "8:40am"]
}
}';
$obj = json_decode($json_data);
//var_dump($obj->vikram);
$value = "8:40am";
$time1 = "time1";
$delete_item;
foreach($obj->vikram as $name=>$node)
{
foreach($node as $i => $time)
{
if($time==$value && $name=$time1)
{
$delete_item = $i;
}
}
}
unset($obj->vikram->time1[$delete_item]);
var_dump($obj->vikram);

Categories