PHP: How to receive JSON array from iPad app - php

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]

Related

PHP: Good way to reconstruct associative array from base64_decode

I want to base64_encode the parameters I send over the url.
Send:
<?php
$product = array("productID"=>"13776", "name"=>"something", "availability"=>"1000");
$url_details = "?id=" . base64_encode(http_build_query($product));
?>
Details
Receive:
<?php
$details = base64_decode($_GET["id"]);
// $product = what is the best way to reconstruct the array from $details?
?>
<p>
Name: <?php echo $products["name"]; ?>
...
</p>
The encoding destroys the array, is there a convenient way to make an associative array out of the string again?
(the encoded url is not sensitive information, but I still do not want it to be flat out readable in the url. If there is a better way to pass this data between pages than what I am doing, let me know)
parse_str is the inverse of http_build_query, so to recover your data:
parse_str(base64_decode($_GET["id"]), $details);
Note that parse_str is harmful if called with only one argument.
And as an aside, you may not want to put this kind of information into the URL to begin with, since it can be easily disclosed to third parties, via the Referrer header, for instance.
You can serialize() your array:
<?php
$product = array("productID"=>"13776", "name"=>"something", "availability"=>"1000");
$url_details = base64_encode(serialize($product));
And then, on your end page unserialize() it:
<?php
$details = unserialize(base64_decode($url_details));
Demo
However you need to be careful and do thorough checking of what you're receiving, since unserialize() will execute arbitrary code sent by the client. For example, I can serialize() my own array, then base64_encode() it, and pass it to the URL in the id parameter, and I can do pretty nasty stuff. So definitely check what you're getting in the request!
From the manual:
Warning
Do not pass untrusted user input to unserialize() regardless of the
options value of allowed_classes. Unserialization can result in code
being loaded and executed due to object instantiation and autoloading,
and a malicious user may be able to exploit this. Use a safe, standard
data interchange format such as JSON (via json_decode() and
json_encode()) if you need to pass serialized data to the user.
Here's a comprehensive article on the matter. Give it a read!
As the manual says, you can also probably accomplish what you're trying to do with json_encode() and json_decode(), though the same warning remains, check that what you're getting is what you're supposed to get and sanitize it.

What is the substring equivalent in PHP

I am getting JSON files but each file has a code/ID with it, in the beginning
i am trying to make a standard way to crop the strings no matter how the code/ID changes.
so these are 2 JSON files:
a:12{/*JSON DATA HERE*/}
a:130 {/*JSON DATA HERE*/}
a:1 {/*JSON DATA HERE*/}
i did not find a way to locate the first occurrence of "{" and include it in the new string that will also include the rest of the JSON string.
in JAVA it would go something like that, but i need it in php:
String myjson = "a:130{/*JSON here*/}";
String newjson = myjson.substring(myjson.indexOf("{"), myjson.length());
how can i do that in php?
This really seems to be a PHP serialized array (through serialize / unserialize) and not JSON.
PHP uses a:<count>{...} to indicate a serialized array in its format.
If you can trust the data (i.e. not user submitted but generated by a trusted application), don't parse it yourself and use unserialize instead.
The reason why you never should use unserialize on user submitted data that you can't verify independently is that it is able to create objects of a user specific selection, and if the object defines __wakeup, it might be able to coerce the object into performing any operation the attacker want. This is also why there is a large warning on the unserialize manual page.

How to pass an object in query string in PHP

I see many questions about passing an array as a query string in PHP, and it seems the prevailing way is using brackets as in key[]=foo&key[]=bar.
However I cannot find a straight answer about how to send an object (or a key=>value associative array - same thing) as a query string.
Currently, however I do it is:
STRING
?foo=bar&hello=world
Then on the server side, I would do:
<?php
$array = array();
$array['foo']=$_GET['foo'];
$array['hello']=$_GET['hello'];
?>
Of course when using $_POST, this is very simple with an ajax request. Any object you send automatically serializes and isn't a problem.
Is this the best way to handle it, or is there some other standard for sending an object in a query string using PHP?
You can use an associative array in a form and in the query string:
object[foo]=bar&object[hello]=world
To build it URL encoded:
$data['object']['foo'] = 'bar';
$data['object']['hello'] = 'world';
echo http_build_query($data);
Yields:
object%5Bfoo%5D=bar&object%5Bhello%5D=world
You can go many levels and/or use dynamically added elements. In general, in text form, it looks just like a PHP array
object[foo][more][even more][]
Or:
object[foo][][more][even more]

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.

Is it safe to call json_decode on user input?

I'm storing a JSON encoded array of integer indexes => integer values in a cookie.
Obviously cookies can be easily manipulated like any other user input, so here's my cookie getter validation:
if ($_COOKIE['myCookie']) { //if cookie exists
$myCookie = json_decode($_COOKIE['myCookie'], true);
if (!is_array($myCookie)) { //in case decoding fails or bad cookie
$myCookie = array(); //sets it as empty array
}
} else { //if cookie doesn't exist, uses an empty array instead
$myCookie = array();
}
Then before using any of the values, I check if it exists in the array and test against a list of white-listed values - this part seems pretty safe but I'm posting it as it's part of the validation:
if (!empty($myCookie[$index])) { //checks if index exists and is truthy
if ($myCookie[$index] !== 1 && $myCookie[$index] !== 2) { //values whitelist
die('Hacking attempt through cookies exploit.');
}
//use the cookie data now
}
Back to the question, is it safe to call json_decode directly on the cookie? Can users manipulate the cookie to run arbitrary code?
I've been reading around many topics on SO so far and what I found is that unserialize() is dimmed unsafe because it calls constructors, but json_decode is technically safe. I've read through their php.net pages but those do not address security directly.
My addon is reaching the live beta very soon, so I'm wondering if calling json_decode directly on the cookie is safe enough or if I should run some type of validation before calling json_decode. I could run a preg_match too, but as I'm testing against a whitelist of values before using them, there should be no problem unless json_decode somehow runs arbitrary code, which it doesn't, right?
I know that json_encode returns NULL if it's not valid JSON, but I'm wondering if this is the right approach or should I add some kind of validation before calling json_decode?
Using json_decode to decode the user input directly has no security problem.
It is just string parsing, won't do any string eval.
json_decode in php is like JSON.parse in javascript, and both of them could be used directly on the user input, they are safe at the decoding time.
But after being decoded, you have to validate the data for your requirement.
Insomuch as json_decode is correctly implemented, it should be safe to just use without extra pre-processing (in fact, that might be worse, given that you might have bugs in your pre-processor).
json_decode will fail if the data is not in json format and otherwise will return an nice array for you to work with. Like Itay said if somebody can exploit this he almost deserves to get in. json_decode doesnt suffer from the risk of sql so I'd say you're fine doing this.
Just make sure you clean anything (or white list, like you already are) before incorporating it in a query.

Categories