PHP for catching POST value - php

How can I catch POST value using PHP for the parameter with multiple third bracket?
Ex.
content[fields][attendees]
content[fields][completed]
Okay, let me post url encoded raw data here:
type=activities.update&objectid=75585970&content%5Bid%5D=75585970&content%5Bname%5D=Order+Received%2F+Processing+request+%28may+need+more+info%29&content%5Bcreated%5D=2013-03-15T16%3A09%3A50%2B00%3A00&content%5Bupdated%5D=2013-03-16T06%3A37%3A01%2B00%3A00&content%5Bviewed%5D=2013-03-16T06%3A35%3A21%2B00%3A00&content%5Blevel%5D=1&content%5Bflagged%5D=0&content%5Btypeid%5D=22&content%5Bparenttypeid%5D=2&content%5Bparent%5D=75585967&content%5Bparentname%5D=Tanmoy+Sadhu+%7C+weew+%7C+RSA&content%5Bitem%5D=75585967&content%5Bitemname%5D=Tanmoy+Sadhu+%7C+weew+%7C+RSA&content%5Bitemtypeid%5D=2&content%5Bposition%5D=2&content%5Bfields%5D%5Battendees%5D=&content%5Bfields%5D%5Bcompleted%5D=1&content%5Bfields%5D%5Btitle%5D=Order+Received%2F+Processing+request+%28may+need+more+info%29+
I've tried with $_POST['content[fields][attendees]'] and $_POST['content\[fields\]\[attendees\]'] but no luck.
Any way to catch that?

Try
echo $_POST['content']['id'];
echo $_POST['content']['name'];
echo $_POST['content']['fields']['attendees'];
etc.
Output from your url parameters:
75585970
Order Received/ Processing request (may need more info)
<-empty string here for attendees

I believe the correct syntax would be
$_POST['content']['field'] etc
so for the example of &content%5Bid%5D=75585970 you can get the value 75585970 by calling
$_POST['content']['id'];
This is because the $_POST value for any particular key is a string (or array in the case the key has brackets).
In this case, $_POST['content'] returns an array of many different key value pairs, and you can access the values using those array keys just like in any multidimensional array.

Related

Not sure why I can't get the values of this array or decode the json

I am making a call to an API which should return a JSON array. I receive this:
Array
(
[0] => {"msg_id":"0t5OxT1ZP9VcF45L2","_text":"I want to reserve","entities":{"intent":[{"confidence":1,"value":"make_reservation","type":"value"}]}}
)
I know it's JSON because a) the docs say that's what I should be getting and b) I ran isJson($response) and got true.
I have tried to use json_decodebut the code just dies when I do (it errs saying it's expecting a string and got an array which makes sense but if I do json_encode that would just further encode the json from what I can understand).
As I understand it, I just need a way to traverse this array and get the "value:" key inside entities: intent:. However I can't figure out how to get it or where I'm wrong.
I have tried doing:
$val = $jsonArray[0]['entitites']['intent'][0]['value'] but nothing comes out.
You are trying to decode a PHP array that has encoded values.
You should try json_decode($jsonArray[0]) instead, so that you decode the value of the first array key, as that is the actual json string.
The data you posted is a php array where the value of the first element of the array is a json string.
json_decode($response[0]);

Getting value from string by index

I have a string of data formatted like so:
[{"pr_a_w":"10","pr_a_we":"10","pr_c_w":"10","pr_c_we":"10"},{"pr_a_w":"20","pr_a_we":"20","pr_c_w":"20","pr_c_we":"20"},{"pr_a_w":"111","pr_a_we":"11","pr_c_w":"111","pr_c_we":"111"}]
The string doesn't have any index/numbers like a regular array would and I'm finding it difficult to extract individual values e.g. with a regular array I could use:
$string[0]["pr_a_w"]
To get the first instance of "pr_a_w" and I could use:
$string[1]["pr_a_w"]
To get the second instance etc.
Is it possible to get single values from this string based on their number?
What you have there is valid JSON (serialized array of objects), so you could use json_decode to translate the serialized data into a native PHP array:
$array = json_decode('[{"pr_a_w":"10","pr_a_we":"10","pr_c_w":"10","pr_c_we":"10"},{"pr_a_w":"20","pr_a_we":"20","pr_c_w":"20","pr_c_we":"20"},{"pr_a_w":"111","pr_a_we":"11","pr_c_w":"111","pr_c_we":"111"}]',true);
$array will then allow you to do exactly what you stated you'd like to do above.
$array[0]["pr_a_w"]; // will give you 10
$array[1]["pr_a_w"]; // will give you 10
Try like this, No need to access with array index. You will get error if you access wrong index.
$json_arr= json_decode('[{"pr_a_w":"10","pr_a_we":"10","pr_c_w":"10","pr_c_we":"10"},{"pr_a_w":"20","pr_a_we":"20","pr_c_w":"20","pr_c_we":"20"},{"pr_a_w":"111","pr_a_we":"11","pr_c_w":"111","pr_c_we":"111"}]',true);
foreach($json_arr as $row){
echo $row['pr_a_w']."<br>";
}

Can a value from $_POST *not* be a string?

In PHP, can a value from the global $_POST array be something else than an array or a string?
The goal is to not have to check if everything is something else than an array or string in a script. If I know what type a variable has, I don't have to do some weird validation. If I expect a string, I don't have to cast everything to a string to make sure it is one.
$_POST["key"] = true;
var_dump($_POST["key"]); // bool(true)
The values set by the environment are strings though.
As per the documentation http://php.net/manual/en/reserved.variables.post.php
An associative array of variables passed to the current script via the HTTP POST method.
So all the data sent is in associative array, in key value pair. There are Numbers (int, float etc), Strings, Arrays (of numbers or strings) and Objects data types.
Using the rule of elimination we can remove the Object from the supported data type, and the remaining left are strings, numbers and array.
Now, if you see the form, the input fields are taking strings, there is no indication that the value entered in the input field is number or string. So to be on safe side all the values which are posted are in strings. The array of elements also have the string values.
When you get the value in $_POST it is simply an array and you can override it any time
$_POST['username'] = 1;
var_dump($_POST['username']); // int (1)
I hope this make some sense
You can cast it to whatever you wish ^^
intval($_POST['INTEGER']);
or simply
(int)$_POST['int']

PHP: How to check if query string or POST vars contain same var twice

It may sound strange, but in my PHP application I need to check if the same variable name has been declared more than once in the query string or POST variables, and return an error value if this is the case. If my application doesn't return an error in this case, it fails a compliance check.
When accessing vars using $_GET, $_POST, etc, PHP only returns the last value given for each variable name. I can't find a way to tell if any variable appeared more than once.
I simply need to find out if the query string or the variables in the POST body contained the same variable name more than once, whatever the values.
Example
My application is supposed to return an error for this query string:
verb=ListIdentifiers&metadataPrefix=oai_dc&metadataPrefix=oai_dc
Note that "metadataPrefix" is defined twice.
My application should not return an error for this query string:
verb=ListIdentifiers&metadataPrefix=oai_dc
POST Requests
$input = file_get_contents('php://input');
(Or $HTTP_RAW_POST_DATA (docs))
GET Requests
$input = $_SERVER['QUERY_STRING'];
Processing
explode('&', $input) and maintain an array - $foundKeys - of keys (the part of each item from explode() before the = character). If you hit a key already defined in $foundKeys, throw the error.
For GET data, check out $_SERVER['QUERY_STRING']. But for POST data, you'll need to read the raw POST data from the php://input stream.
So something like this:
// GET data:
$raw = $_SERVER['QUERY_STRING'];
// Or for POST data:
$raw = file_get_contents("php://input");
if (substr_count('&'.$raw, '&metadataPrefix=') > 1)
die('Error');
print_r($raw); //post vars
PHP $_POST will always set only one value per variable unless the request variable name ends with [].
If you have no control over the variables that are sent, you may try using $_SERVER['RAW_HTTP_POST_DATA'] to get the original POST request data before parsed, then you can use the parse_str() function to parse that string.
Just be careful that PHP configuration may have disabled setting the RAW_HTTP_POST_DATA value. In that case, you cannot do anything to solve your problem.
Not completely foolproof but this might work
$occurrences = substr_count($_SERVER['QUERY_STRING'], 'metadataPrefix=');
If you expect multiple values named the variable with square brackets in the end. This way you get an array for that variable. If multiple values are set, the array will have multiple entries.
<input type="checkbox" name="my_var[]" value="a">
<input type="checkbox" name="my_var[]" value="b">
$_POST['my_var'] will be an array with either 'a' or 'b', both, or none depending on the checkboxes used.

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