PHP - 使用JSON解码变量的奇怪行为

时间:2015-03-27 09:53:05

标签: php json curl slim

我的应用程序中有一个相当奇怪的行为,并且没有想法。我正在尝试使用Slim创建一个小型REST API。我使用cURL来调用页面,请求是JSON格式。 Slim读取正文并使用json_decode(value, true)进行解码以返回数组。请找到帖子功能:

$app->post('/users', function () use ($app, $log)
{
   $body = $app->request()->getBody();
   echo $body['username']; // Will throw Illegal string offset 'username'

   if (isset($body["username"]) && isset($body["password"]))
   {
      echo $body['username']; // Will work
   }
   else
   {
      throw new \API\Exception\ValidationException("Invalid arguments"); // Is thrown all the time
   }
});

问题1 : 即使$body作为数组从json_decode返回,访问成员也会抛出Illegal string offset错误并停止代码。

 var_dump($body); // array(2) { ["username"]=> string(8) "testuser"    ["password"]=> string(8) "testpass" }
 echo is_array($body); // 1
 echo $body['username']; // Illegal string offset 'username'
 echo array_key_exists('username', $body); // Illegal string offset 'username'

我找到的解决方案是放置isset($body[key]),代码将继续运行,就像没有任何反应一样。让我们说这是一个修复,但我不喜欢。我想明白为什么会这样。然而,它仍然导致我遇到问题2.

问题2 : 如果我尝试在isset块之外放置一个异常,它将每次抛出它(即使参数有一个值或不存在)。

这对我来说毫无意义,我尝试了所有想到的东西。我还有一个GET /users/:username,我也使用Exception验证用户名,所有工作都很好。它只在从JSON中编码的POST读取参数后才会发生。

我已在IIS(服务器在Windows上)和Apache以及PHP 5.5和5.6(都是x64)下测试过。

我做错了什么?提前谢谢。

编辑:

也是cURL电话:

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_1);
curl_setopt($ch, CURLOPT_CAINFO, "pemPath"); //Intentionally deleted the CAinfo path
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_NTLM);
curl_setopt($ch, CURLOPT_USERPWD, "myauth"); //Intentionally deleted credentials
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_URL, "https://localhost/api/v1/users");
curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-HTTP-Method-Override: POST", "Content-Type: application/json; charset=UTF-8"));
$postArr = array("username" => "testuser", "password" => "testpass");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
$result = curl_exec($ch);

0 个答案:

没有答案