How to query parameters in URL - json api - php

I have to call api url to access the json object from it. in its tutorial, they provide some variables we can access through url, these variables have names different of the attributes name of the json object.
ex: url&parm1=val1
json object
{
"parm1_name": "val1"
}
My question:
How to return specific values depend on the attributes of the json object?
Do we have to use the parameter names which are provided on their website?
what the difference between "?pram1=val" and "pram1=:val"
How to query as we do in databases using greater or less than?
I use PHP and crul to retrieve the json object.

The value that each parameter/s return should be documented by the api and is up to the provider.
Yes, you have to use the parameters the api/website requires to return the value. If the api/website expects a value to return something then you have to provide the expected value. That also means the website will only recognize values that they look for.
The paramaters are key and value so
?param=val1 => key "param" equals "val1"
?param=:val1 => key "param" equals ":val1"
Unless the api provides a way to do then you can't. The limitations of what you can do is set by the api.
Api is essentially this:
<?php
// it gets ?id=val
// so if the GET parameters were ?id=1&name=blue&do=add
// it would only recognize id parameters the other parameters wouldnt change a thing
$val = $_GET["id"];
if $val == 1 {
return $data;
}
?>
API must provide a way for you to e.g. search for "greater & less than" otherwise you cannot do it.

Related

Laravel Key Value Pair in Get Request

I'm using Laravel 5.4 and Axios to make async requests to my backend and retrieve data based on the get request parameters of my api endpoint.
I can see in inspector I'm making the following request to the server:
https://website.com/api/users?page=1&sort=%7B%22fieldName%22:%22lname%22,%22order%22:%22asc%22%7D&filter=
Which decodes to:
https://website.com/api/users?page=1&sort={"fieldName":"lname","order":"asc"}&filter=
Looks like I can successfully get pieces of the query via:
return $request->query('sort');
which returns:
data:
fieldName: "lname"
order: "asc"
But when I use:
return $request->query('sort.fieldName');
I don't get anything. Should I not be using the dot notation? How do I get each key / value pair of the sort input? Thanks for any help!
I thought you could use dot notation, but at any rate you could try just converting it from json to an associative array.
$sort = json_decode($request->query('sort'), true);
This should then allow you to do something like, $sort[‘fieldName’]. The true parameter tells the decode to turn it into an associative array versus being returned an object.

Differences between query and input

What are differences between
$request->query()
And
$request->input() in Laravel?
Both of them return the same result.
It's mentioned directly in the official documentation:
While the input method retrieves values from entire request payload
(including the query string), the query method will only retrieve
values from the query string:
https://laravel.com/docs/5.5/requests
One important part of this two methods,
$request->input() :: Can work with any HTTP verb( Ex. GET,POST,..)
$request->query() :: Can only retrieve data passed from query string( GET method )
If you use only query string to pass data, you will get the same result for both the methods, but if you use any other HTTP method(May be with Query String values), you will find the difference.
in native PHP coding.
$request->input() is the equivalent of $_REQUEST //this is either querystring or form-data submission.
$request->query() is just a straight forward $_GET //this is querystring

Convert key-value JSON to object and refer individual values directly

I am making a web app. In one part of it, I have JS send a string(in json format) to PHP.
The value php receives is:
{"date":"24-03-2014","Cars":["Cheap","Expensive"]}
Now, this is saved in a variable $meta. The problem I am facing is, as to how do I convert this string into an object and reference each individual entry separately.
I have tried json_decode and json_encode
and then I have referenced each variable using $meta.["date"] and $meta.date but nothing seams to work. I am getting just { as the output.
What's the correct way to do this?
$str = '{"date":"24-03-2014","Cars":["Cheap","Expensive"]}';
$obj = json_decode($str);
echo $obj->date;
// 24-03-2014
Usually a $my_obj = json_decode($_POST['jsonstring'], 1); (true supply means it'll be returned as an assoviative array) should be the way to go. If I were you I'd probably try a var_dump($my_obj); to see what actually comes through. If it doesn't work you'll want to make sure that you correctly submit a valid json string, e.g. JSON.stringify();
You should check out the PHP doc page for json_decode here.
By default, unless you pass true as the second parameter for json_decode, the function call will return an object, which you can access the members of by using:
$meta->date
The arrow operator will allow you to access object values, not the square brackets or a dot.

PHP: How to receive JSON array from iPad app

Disclaimer: I am fairly new to using json.
I am trying to use php to receive json data from an iPAd application. I know how to convert json to an array in php, but how do I actually receive it and store it into a variable so it can be decoded?
Here are a couple examples that I have tried based on google and stackoverflow searches.
$json_request = #file_get_contents('php://input');
$array = json_decode($json_request);
AND ALSO
$array = json_decode($_POST['data'], true);
Any suggestions?
You have the basic idea already.
you should test that the value is set and also strip extra slashes from the incoming string before trying to parse it as JSON.
if(isset($_POST['data'])){
$array = json_decode(stripslashes($_POST['data']),true);
//$array now holds an associative array
}//Data Exists
It also would not be a bad idea before you start working with the array to test that the call to json_decode() was successful by ensuring that $array isn't null before use.
If you do not fully trust the integrity of the information being sent you should do extended checking along the way instead of trusting that a given key exists.
if($array){ // Or (!is_null($array)) Or (is_array($array)) could be used
//Process individual information here
//Without trust
if(isset($array['Firstname'])){
$CustomerId = $array['Firstname'];
}//Firstname exists
}//$array is valid
I in-particular like to verify information when I am building queries dynamically for information that may not be required for a successful db insert.
In the above example $_POST['data'] indicates that what ever called the PHP script did so passing the JSON string using the post method in a variable identified as data.
You could check more generically to allow flexibility in the sending method by using the $_REQUEST variable, or if you know it is coming as via the get method you can check $_GET. $_REQUEST holds all incoming parameters from both get and post.
If you don't know what the name of the variable coming in is and want to play really fast and loose you could loop over the keys in $_REQUEST trying to decode each one and use the one that successfully decoded (if any). [Note: I'm not encouraging this]

PHP - Data after "?" in URL displays different information

I know the title isn't very clear. I'm new to PHP, so there might be name for this kind of thing, I'll try to explain as best as I can. Sometimes in a URL, when using PHP, there will be a question mark, followed by data. I'm sorry, I know this is very noobish, but I'm not sure what it's called to look for a tutorial or anything. Here is what I mean:
http://www.website.com/error_messages.php?error_id=0
How do you configure it to display different text depending on what the number is (in this example it's a number)
Could somebody please tell me what this is called and how I could do this? I've been working with PHP for a couple days and I'm lost. Thank you so very much for understanding that I am very new at this.
That "data" is the URL querystring, and it encodes the GET variables of that HTTP request.
Here's more info on query strings: http://en.wikipedia.org/wiki/Query_string
In PHP you access these with the $_GET "super-global" variable:
// http://www.website.com/error%5Fmessages.php?error%5Fid=0
// %5F is a urlencoded '_' character, which your webserver will most likely
// decode before it gets to PHP.
// So ?error%5Fid=0 reaches PHP as the 'error_id' GET variable
$error_id = $_GET['error_id'];
echo $error_id; // this will be 0
The querystring can encode multiple GET variables by separating them with the & character. For example:
?error_id=0&error_message=Something%20bad%20happened
error_id => "0"
error_message => "Something bad happened"
In that example you can also see that spaces are encoded as %20.
Here's more info on "percent encoding": http://en.wikipedia.org/wiki/Percent-encoding
The data after the question mark is called the "query string". It usually contains data in the following format:
param1=value1&param2=value2
Ie, it is a list of key-value pairs, each pair separated with the ampersand character (&). In order to pass special characters in the values, they have to be encoded using URL-encoding format: Using the percent sign (%) followed by two hexadecimal characters representing the character code.
In PHP, parameters passed via the query string are automatically propagated to your script using the super-global variable $_GET:
echo $_GET['param1']; // will produce "value1" for the example above.
The raw, unprocessed query string can be retrieved by the QUERY_STRING server variable:
echo $_SERVER['QUERY_STRING'];
It's called the query string.
In PHP you can access its data via the superglobal $_GET
For example:
http://www.example.com/?hello=world
<?php
// Use htmlspecialchars to prevent cross-site scripting attacks (XSS)
echo htmlspecialchars($_GET['hello']);
?>
If you want to create a query string to append to a URL you can use http_build_query():
$str = http_build_query(array('hello' => 'world'));
As previously described, the data after the ? is the querystring (or GET data), and is accessed using the $_GET variable. The $_GET variable is an array containing the name=value pairs in the querystring.
Here is a breif description of $_GET and an example of it's usage:
http://www.w3schools.com/php/php_get.asp
Data can also be submited to a PHP script as POST data (found in the $_POST variable), which is used for passwords, etc, and is not stored in the URL. The $_REQUEST variable contains both POST and GET data. POST and GET data usually originates from being entered into a web form by a user (but GET data can also come directly from a link to an address, like in your example). More info about using web forms in PHP can be found here:
http://www.w3schools.com/php/php_forms.asp
its called "query string"
and you can retrieve it via $_SERVER["QUERY_STRING"]
or you can loop through $_GET
in this case the error_id, you can check it by something like this
echo $_GET['error_id'];
The term you are looking for is GET. So in php you need to access the GET variables in $_GET['variable_name'], e.g. in the example you gave $_GET['error_id'] will contain the value 0. You can then use this in your logic to echo back different information.
The bit after the question mark is called a Query String. The format is typically, although not necessarily always, key-value pairs, where the pairs are separated by an ampersand (&) and the value is separated from the name by an equals sign (=): ?var1=value1&var2=value2&.... Most web programming environments provide an easy way to access name-value pairs in this format. For example, in PHP, there is a superglobal, which is an associative array of these key-value-pairs. In your example, error_id would be accessible via:
$_GET['error_id']
The reason for the name "GET" is that query string variables are typically associated with a HTTP GET request. POST requests can contain GET variables too, whereas GET requests can't contain POST variables.
As to the rest of your question, you could approach the text issue in a number of ways, the simplest being switching on the error id:
$error_id = isset($_GET['error_id']) ? $_GET['error_id'] : 0;
switch($error_id) {
case 1:
echo "Error 1";
break;
default:
echo "Unknown Error";
break;
}
and more complex ways involve looking up the error message from a file, database or what have you.

Categories