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


How to recieve post json data on PHP server page

我有以下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 数据是否有任何问题?请帮忙。

你可能有raw_post_data。

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

终于在你们的帮助下,我自己想通了。网络服务.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 数据。