POST is empty when curling JSON

I use curl to send:

curl -i -H "Accept: application/json" -H "Content-type: application/json" -X POST -d "{firstname:james}" http://hostname/index.php 

I am trying to display POST like this in index.php

 <?php die(var_dump($_POST)); ?> 

What are the exits

 array(0) { } 

I must not understand something about sending JSON data via POST

thank you for your time

+6
source share
2 answers

$_POST is an array that is populated only if you send the POST body in a URL-encoded format. PHP does not parse JSON automatically and therefore does not populate the $_POST array. You need to get the original POST body and decode the JSON yourself:

 $json = file_get_contents('php://input'); $values = json_decode($json, true); 
+21
source

$_POST only works if you send data in an encoded form. You are sending JSON, so PHP cannot parse it into the $_POST array.

You need to read directly from the POST body.

 $post = fopen('php://input', r); $data = json_decode(stream_get_contents($post)); fclose($post); 
+5
source

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


All Articles