Access PUT-data in PHP - php

I want to access JSON data sent with the PUT-method, as a payload to a PHP-backend.
From what I've read, the data should be available in the php://input stream, and I should be able to fetch it using.
file_get_contents('php://input');
This works for POST-requests, but just returns an empty string when using PUT,
although I can find the PUT-data as the first key in the $_POST variable, like this:
array(
"{"latLngPosition":null,"pixelPosition":null,"id":"1","marking":"012312312313"}" => ""
)
It doesn't seem right to fetch the data this way, so I wonder what I might do wrong when fetching using php://input.
I'm using nginx with fastcgi to run PHP.

Related

Reading JSON from HTTP POST using PHP (Typeform)

I'm having trouble reading JSON data (using PHP) that's coming in from a webhook (Typeform.)
I've tried the solution provided Here but I'm still getting a null array. My code is exactly the same as the example shown in the link (although I'm not accessing particular arrays, I just want to read the data.) All my test deliveries are returning 200, so I'm just a bit stuck.
$data = json_decode(file_get_contents('php://input'));
var_dump($data);
TypeForm runs the page, They'll get the var_dump response...
When you run the page, you haven't posted anything so $data is empty, therefore null
Try saving $data to a file, then when TypeForm POSTS to it, You can see what the POST contents were, in that file
file_put_contents("webhookData.txt",$data, FILE_APPEND);

PHP POST method json_decode return NULL

I'm using sencha touch and I'm sending data to php REST server to save it to database, in firebug I can see the parameters that sencha touch send to php side, but in php I have this code:
parse_str(file_get_contents("php://input"),$post_vars);
$info=$post_vars['customers'];
$data=json_decode(stripslashes($info),true);
The json_decode return NULL, the get_magic_quotes_gpc is off I also tried utf8_encode but always I got NULL, I tried var_dump and at the response I got extra text:
array(1) {
["customers"]=>
string(50) "{"c_name":"test","c_tel":"08-05852821","id":"112"}"
}
I don't know how to continue, before the var_dump the post contains:
{"success":{"customers":"{\"c_name\":\"test\",\"c_tel\":\"08-05852821\",\"id\":\"112\"}"}}
I tried stripslashes but I got also NULL...
Any idea...
Based on your comment, I would access $_POST directly:
$info = json_decode($_POST['customers'], true);
echo $info['c_name'];
There are three possibilities how Jason can be transmitted.
First, it can be a get variable with a Name (index.php?data={success:true}), this only Works for Short json strings.
Second, it can be a post variable with a Name ( will be Sent as x-www-form-urlencoded)
Third, you can post only json (Store.sync does that)
Only the Latter will be accessed via php://Input, it Seems as of you use the Second.

Traverse array structure with string

Can I store a pre-made array traversal?
I want to store several API calls, and also how I get to the relevant information from their response.
For example:
$url = 'http://maps.googleapis.com/maps/api/elevation/json?locations='.$location->$latitude.','.$location->$longitude.'&sensor=true';
$response = json_decode(file_get_contents($url), true);
$result = $response['results'][0]['elevation'];
Can I save this part as a string, for storage in my DB or a variable:
$elevation = "['results'][0]['elevation']";
Then later somehow use it to parse the response, ie.
$result = $response[$elevation];
The answer is no, sorry ! you will need to store your $response as it is and call it later on using the correct format $response['results'][0]['elevation']
You may however want to use serialize() if the problem is about how to persist the array into your database:
$db->insert(serialize($reponse));
then when you retrieve the response from your db use unserialize:
$response=unserialize($db->fetchReponse());
$elevation=$response['results'][0]['elevation'];
EDIT
Based on your comment below it seems what you need is a Cache. Whereby prior to sending the request to the web service API, your application checks in a cache to see if you already have the data available locally. As above example you would most likely want to serialize the PHP array or simply cache the raw response, given that it is in JSON format (PHP serialization will create something very similar anyway).
You would create the Cache key from the query params : location, etc.
Your cached object can be stored in a DB if you choose or on the file system, or even in Memory.
Check out ZF2 Cache component :
http://framework.zend.com/manual/2.0/en/modules/zend.cache.storage.adapter.html

$_POST is empty even though CONTENT_LENGTH is correct

I've got an HTTP POST pointed at two different places.
The first location is handled by a thirdparty solution, so I can't see how they're handling the data (which they must be because the values are getting through and I'm seeing results).
In my location, I have an NGINX server (which has never had any problems before with lots of use). I am using php to read the POST data, and I expect the content to be in the $_POST variable as the POST is $_SERVER["CONTENT_TYPE"] => "multipart/form-data"
But, even though the type and the $_SERVER["CONTENT_LENGTH"] are correct, I'm getting nothing in my $_POST, $_REQUEST, and when checking file_get_contents('php://input') there is nothing inside either.
The body is a very small json lump (<1k). Always an array of objects.
To see what's in the arrays I used echo json_encode( array( "GET" => $_GET, "POST" => $_POST, "REQUEST" => $_REQUEST, "SERVER" => $_SERVER ) )
I've run out of ideas of what to check now.
the entry $_SERVER["PHP_SELF"] has a strange garbling possibly due to the path delimiters?
How to post JSON to PHP with curl lead me to the solution:
Don’t forget to send it as application/json
Once I did that, the data came through in the body. This helps me, but I'm still curious as to why the third party receiver can handle the data as it was.

AS3 to PHP, JSON type error? C/Ping the string works, $_posting the JSON itself doesn't

I'm passing a JSON object from flash AS3 to PHP, which is then taken apart and passed to the DB.
In Flash:
var jsonObject:Object = JSON.encode(currentlySelectedArray);
In PHP:
$json_pieces_array = $_POST['jsonArray'];
$json_obj = json_decode($json_pieces_array, true);
When I test my code by copy/pasting the output of 'trace (saveDataJSON.ToString());' and putting it into my '$_POST['jsonArray'] = '[[Valid JSONLint checked JSON here.]]', everything works fine and it gets pushed to the database.
But when I don't meddle and use the flash-sent $_POST, nothing pushes to the MYSQL DB.
My question is twofold:
1) What's the best way to bug test this sort of complication? I'm in the Flash interface.
2) What sorts of things should I be looking for? I already checked that the JSON being encoded was valid. Is there some sort of weird typecasting I'm missing?
At first you have to debug request from flash. You can do it in several ways:
create dummy file that does var_dump($_REQUEST);;
add file_put_contents('my_dump_file.txt', var_export($_REQUEST, true)); in existing script;
check your webserver logs;
debug you script with debugger (xdebug or similar).
Then you should check your PHP script. Try to var_dump($_REQUEST); on the top and exactly before json_decode. It can be so that $_POST['jsonArray'] is overwritten somewhere else.
I guess that the problem is between flash and php. In most cases there is simply misspelling or $_POST is mixed with $_GET.

Categories