BENN1TH BENN1TH - 4 years ago 164
JSON Question

PHP POST via JSON is empty

I have a basic form that post to PHP file.

<form action="index.php" method="POST">
<input name="operation" id="operation" placeholder="operation" />
<br>
<input id="name" name="name" placeholder="Name" />
<br>
<input id="email" name="email" placeholder="Email"/>
<br>
<input id="password" name="password" placeholder="Password"/>
<br>
<button type="submit" >POST</button>
</form>


problem is the operation is posting NULL or empty via the index file below.
I am using the basic php://input to get encoded via json.

if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$data = json_decode(file_get_contents('php://input'));

if(isset($data -> operation)){

$operation = $data -> operation;
echo $operation;
if(!empty($operation)){

}else{

//$operation is empty ...

}

}else{

//$operation is not set ...

}

}


However echoing the file_get_contents('php://input') displays the correct values from the posted form.

Any reason why the $operation return is always empty?

Answer Source

Your data should be prepared before convert to Json format Try this code :) I test this Code, it work. Good Luck



    if ($_SERVER['REQUEST_METHOD'] == 'POST')
{

    $data = file_get_contents('php://input');
    $data = str_replace('=','":"',$data);
    $data = str_replace('&','","',$data);
    $data = '{"'.$data.'"}';

    $data = json_decode($data);

    if(isset($data->operation)){

      $operation = $data -> operation;
      echo $operation;
       if(!empty($operation)){
            echo "NOT EMPTY";
       }else{

            echo "IS EMPTY";
           //$operation is empty ...

       }

     }else{
            echo "NO OPERATION";
          //$operation is not set ...

     }

  }


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download