【问题标题】:URL encoding seems to get in the way of properly json encoding/decoding in my PHP programURL 编码似乎妨碍了我的 PHP 程序中正确的 json 编码/解码
【发布时间】:2011-06-22 19:03:39
【问题描述】:

我正在实现一个 PHP 脚本,它接收一个 HTTP POST 消息,正文中包含一个 json 字符串,与“报告”参数相关联。所以 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 自动选择。当我将其设置为“应用程序/json”时,我的 PHP 脚本看不到任何参数,因此找不到“报告”变量。 我想 url 编码出了点问题,但我在这里迷失了如何让 json 交叉。

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

无论如何,我希望这个问题能得到一些明确的说明。 提前致谢。

节食

【问题讨论】:

  • 问题确实是魔术引号,显然它在我的 MAMP 版本中默认启用。如果我现在将它作为键/值对发送(json 是值),并且没有定义内容类型,它就像一个魅力。但是不能使用内容类型 application/json ,但我想这样做的原因是我违反了一些 RFC 类型的东西,我明确不想这样做。非常感谢 @johncartwright 和 @hakre 的出色帮助!
  • 提示:选择一个答案作为“答案”,例如约翰的。
  • @hakre :完成,感谢您的提示 :)

标签: php json http urlencode simpletest


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    为了快速修复,请尝试:

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

    更好,disable magic quotes GPC。 G=Get,P=Post,C=Cookie。

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

    阅读here how to disable magic quotes

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-10
      • 2010-11-06
      • 2015-02-25
      • 1970-01-01
      • 2020-11-26
      • 2011-08-05
      • 2011-11-09
      • 1970-01-01
      相关资源
      最近更新 更多