开发者

URL encoding seems to get in the way of properly json encoding/decoding in my PHP program

开发者 https://www.devze.com 2023-03-14 22:29 出处:网络
I\'m implementing a PHP script which receives an HTTP POST message with in the body a json string, tied to a \'report\' parameter. So HTTP POST report=.

I'm implementing a PHP script which receives an HTTP POST message with in the body a json string, tied to a 'report' parameter. So HTTP POST report=. I'm testing this out with SimpleTest (PHP Unit Testing).

I build the json:

$array = array("type" => "start"); // DEBUG
$report = json_encode($array);

I send the POST:

$this->post(LOCAL_URL, array("report"=>$json));

(calls a method in the WebTestCase class from SimpleTest).

SimpleTest says it sends this:

POST /Receiver/web/report.php HTTP/1.0
Host: localhost:8888
Connection: close
Content-Length: 37
Content-Type: application/x-www-form-urlencoded

report=%7B%22type%22%3A%22start%22%7D
开发者_如何学Python

I receive as such:

$report = $_POST['report'];    
$logger->debug("Content of the report parameter: $report");    
$json = json_decode($report);

The debug statement above gives me:

Content of the report parameter: {\"type\":\"start\"}

And when I decode, it gives the error

Syntax error, malformed JSON

The 'application/x-www-form-urlencoded' content-type is automatically selected by SimpleTest. When I set it to 'application/json', my PHP script doesn't see any parameters and as such, can't find the 'report' variable. I suppose something is going wrong with the url encoding, but I'm lost here as to how I should get the json accross.

Also, what is the usual practice here? Does one use the key/value approach even if you just send an entire json body? Or can I just dump the json string in the body of the HTTP POST and read it out somehow? (I had no success in actually reading it out without a variable to point to).

Anyway, I hope the problem is somewhat clearly stated. Thanks a bunch in advance.

Dieter


It sounds like you have magic quotes enabled (which is a big no-no). I would suggest you disable this, otherwise, run all your input through stripslashes().

However, it is better practice to reference the POST data as a key/value pair, otherwise you will have to read the php://input stream.


For the quick fix, try:

$report = stripslashes($_POST['report']);

Better, disable magic quotes GPC. G=Get, P=Post, C=Cookie.

In your case Post. Post values get automatically ("magic") quoted with a single slash.

Read here how to disable magic quotes.

0

精彩评论

暂无评论...
验证码 换一张
取 消