Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST empty when curling JSON

Tags:

json

post

php

curl

I'm using curl to send this:

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

I'm trying to display POST like this in index.php

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

Which outputs

array(0) {
}

I must be misunderstanding something about sending JSON data via POST

Thank you for your time

like image 743
PandemoniumSyndicate Avatar asked Aug 16 '12 15:08

PandemoniumSyndicate


People also ask

How do I POST JSON with Curl?

To post JSON data using Curl, you need to set the Content-Type of your request to application/json and pass the JSON data with the -d command line parameter. The JSON content type is set using the -H "Content-Type: application/json" command line parameter. JSON data is passed as a string.

Does Curl POST request?

To make a POST request with Curl, you can run the Curl command-line tool with the -d or --data command-line option and pass the data as the second argument. Curl will automatically select the HTTP POST method and application/x-www-form-urlencoded content type for the transmitted data.

How do you set Curl to POST?

To POST a file with curl , simply add the @ symbol before the file location. The file can be an archive, image, document, etc.

Does Curl use JSON?

by David Callaghan on January 20th, 2022 | ~ 3 minute readcURL is frequently used by developers working with REST API's to send and receive data using JSON notation.


1 Answers

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

$json = file_get_contents('php://input');
$values = json_decode($json, true);
like image 75
deceze Avatar answered Sep 29 '22 08:09

deceze