umesh
umesh

Reputation: 231

php not getting data from Request, posting from curl

I am firing a curl request from command line.

My curl request looks like:

curl -X POST -H "Accept: application/json"  -H "Content-type: application/json"  -d '{ "BookingByCustomer" : "testUser", "BookingDate" : "11111111", "TotalCost" : "11", "NetAmount"  : "11" }' http://serverIP:port/test.php 

My PHP code:

    <?php
   /** global variables */
    $request_called = ($_SERVER['REQUEST_METHOD'] == 'GET') ? 'GET' : 'POST';

    if($request_called == 'POST')
    {
         handle_post_request();
    }
    if($request_called == 'GET')
     {
       handle_get_request();
     }

    function handle_get_request (){
      echo "Get Request has been called!";   
   }

    function handle_post_request (){
   $json = $_SERVER['HTTP_JSON'];
    print_r ($_SERVER);
   }
 ?>

but $_SERVER doesn't seems to have json data. Did i miss something??

Upvotes: 1

Views: 1340

Answers (3)

bestprogrammerintheworld
bestprogrammerintheworld

Reputation: 5520

This function returns the value of $_SERVER and not the value of the $json-variable.

  function handle_post_request (){
   $json = $_SERVER['HTTP_JSON'];
    print_r ($_SERVER);
   }

And second I believe you have to use $_POST to get this working:

  function handle_post_request (){
   $json = $_POST['HTTP_JSON'];
    print_r ($json, true);
   }

Upvotes: 0

Dehalion
Dehalion

Reputation: 757

There is no such entry as $_SERVER['HTTP_JSON'] in $_SERVER. You need to get the POST content from $_POST.

But as you are not giving your JSON data a variable name you should get the raw POST content with

$json = file_get_contents("php://input");

Another solution would be to assign a variable name to your JSON data:

curl -X POST ... -d 'HTTP_JSON={ ... }'

As long as you have no forbidden characters (like ? or &) in your JSON you are safe, otherwise you would also have to URL encode your JSON string. That's why I suggested the first solution using php://input. This way you don't have to care about URL encoding.

Upvotes: 3

Matt
Matt

Reputation: 5428

You are posting the information with curl so use $_POST instead of $_SERVER.

function handle_post_request (){
    $json = $_POST['HTTP_JSON'];
    print_r ($_POST);
}

Upvotes: 0

Related Questions