3

我正在实现一个 PHP 脚本,它在正文中接收一个带有 json 字符串的 HTTP POST 消息,该字符串与“报告”参数相关联。所以 HTTP POST 报告=。我正在使用 SimpleTest(PHP 单元测试)对此进行测试。

我构建了json:

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

我发送 POST:

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

(从 SimpleTest 调用 WebTestCase 类中的方法)。

SimpleTest 说它发送这个:

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

我收到这样的:

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

上面的调试语句给了我:

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

当我解码时,它给出了错误

Syntax error, malformed JSON

'application/x-www-form-urlencoded' 内容类型由 SimpleTest 自动选择。当我将其设置为“application/json”时,我的 PHP 脚本看不到任何参数,因此找不到“report”变量。我想 url 编码出了点问题,但我在这里迷失了我应该如何让 json 交叉。

另外,这里的通常做法是什么?即使您只发送整个 json 正文,是否也使用键/值方法?或者我可以将 json 字符串转储到 HTTP POST 的正文中并以某种方式读出吗?(我没有成功地在没有变量指向的情况下实际读出它)。

无论如何,我希望这个问题有点清楚地说明了。提前感谢一堆。

迪特

4

2 回答 2

4

听起来您启用了魔术引号(这是一个很大的禁忌)。我建议你禁用它,否则,通过 stripslashes() 运行所有输入。

但是,最好将 POST 数据引用为键/值对,否则您将不得不读取 php://input 流。

于 2011-06-22T19:07:08.107 回答
2

对于快速修复,请尝试:

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

更好的是,禁用魔术引号 GPC。G=获取,P=发布,C=Cookie。

在你的情况下Post。帖子值会自动(“魔术”)用一个斜杠引用。

在此处阅读如何禁用魔术引号

于 2011-06-22T19:11:28.640 回答