如何在PHP服务器页面上接收post json数据

时间:2014-11-14 07:07:00

标签: php json api

我有以下json正文,我通过API从应用发布。

{
  "GetUserMasterOperation" : "GetUserMasterOperation",
  "do" : "INSERT",
  "Email" : "test@gmail.com",
  "UserName" : "test",
  "Password" : "123",
  "MobileId" : "BB767CA0"
} 

在服务器端,我使用这个PHP代码来检索'webservices.php'中的json:

<?php
include_once("lib/api_class.php");
$api= new API();

if($api->get_request_method()=='POST' && isset($_POST['GetUserMasterOperation']))
{
    header('Content-type: application/json');
    $api->UserMasterOperation($_POST);
}
?>

现在是'api_class.php'

<?php
require_once "dbconnect.php";
class API extends dbconnect
{           
    public function __construct()
    {
        $db=new dbconnect;
        $db->connect();
    }

    public function UserMasterOperation($postJson)
    {       
        $post=json_decode($postJson,true);  

        if($post['do']=='INSERT')
        {            
              $status = false;
              $dt= $this->sanitate($post);
              $MobileId=$dt['MobileId'];
              $WearableId=$dt['WearableId'];
              $UserName=$dt['UserName'];
              $Email=$dt['Email'];
              $pass=md5(trim($dt['Password']));

              $sql="INSERT INTO `usermaster` SET `MobileId`='".$MobileId."', `WearableId`='".$WearableId."',`UserName`='".$UserName."', `Email`='".$Email."', `Password`='".$pass."', `Status`='Active', `Deleted`='no', `CrDate`=NOW()";

              if(mysql_query($sql))
              { 
                $last_id=mysql_insert_id();    
                  if(mysql_affected_rows()==1)
                  {                     
                    $result='Your account has been created.';
                    $response=array('stauscode'=>200,'msg'=>$result, 'userID'=>$last_id);

                    return $this->response($this->json($response), 200);
                  }
                  else
                  {
                    return $this->response($this->json(array('stauscode'=>400,'msg'=>'Bad request')), 400);            
                  }
              }         
        }    

        else
        {
            return $this->response($this->json(array('stauscode'=>800,'msg'=>'Missing Parameters')), 800);            
        }
    }
}
?>

但作为回报,我一无所获。收到发布的json数据有什么问题吗?请帮忙。

2 个答案:

答案 0 :(得分:1)

您可能有raw_post_data

您可以从php://input流中读取此数据,或者在php.ini文件中将always_populate_raw_post_data配置变量设置为true,以便始终将原始数据填充到$_POST变量。

答案 1 :(得分:0)

最后在你们的帮助下,我自己想出来了。 webservices.php应该是这样的:

<?php
include_once("lib/api_class.php");
$api= new API();
header('Content-type: application/json'); 
$input=json_decode(file_get_contents('php://input'),TRUE);

if($api->get_request_method()=='POST' && isset($input['GetUserMasterOperation']))
{

    $api->UserMasterOperation($input);
}

?>

就是这样。您将在服务器端页面上获得整个json数据。