POST JSON data via CURL and capture

I am trying to pass json data as parameter for cURL POST. However, I was stuck in grabbing him and saving him on db.

cURL file:

$data = array("name" => "Hagrid", "age" => "36"); $data_string = json_encode($data); $url = 'http://localhost/project/test_curl'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json') ); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); $result = curl_exec($ch); //based on http://www.lornajane.net/posts/2011/posting-json-data-with-php-curl 

test_curl file:

  $order_info = $_POST; // this seems to not returning anything //SAVE TO DB... saving empty... 

What did I miss? Weew ....

+4
source share
2 answers

You send the data as raw JSON in the body, it will not populate the $_POST variable.

You need to do one of two things:

  • You can change the content type to the one that fills the $_POST array
  • You can read the original body data.

I would recommend option two if you have control over both ends of the connection, as it will keep the request body size to a minimum and maintain bandwidth over time. (Editing: I did not particularly emphasize here that the amount of bandwidth that it will save is negligible, only a few bytes per request, this will only be an urgent problem, this is a very high traffic environment. However, I still recommend option two, because what is the cleanest way)

In your test_curl file do the following:

 $fp = fopen('php://input', 'r'); $rawData = stream_get_contents($fp); $postedJson = json_decode($rawData); var_dump($postedJson); 

If you want to populate the $_POST variable, you will need to change the way data is sent to the server:

 $data = array ( 'name' => 'Hagrid', 'age' => '36' ); $bodyData = array ( 'json' => json_encode($data) ); $bodyStr = http_build_query($bodyData); $url = 'http://localhost/project/test_curl'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/x-www-form-urlencoded', 'Content-Length: '.strlen($bodyStr) )); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $bodyStr); $result = curl_exec($ch); 

Raw, unencoded JSON will now be available in $_POST['json'] .

+20
source

Use the following php function to send data using the php curl function in x-www-form-urlencoded format.

 <?php $bodyData = http_build_query($data); //for x-www-form-urlencoded ?> 
0
source

Source: https://habr.com/ru/post/1393725/


All Articles