Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to post JSON to PHP with curl

Tags:

rest

post

php

I may be way off base, but I've been trying all afternoon to run the curl post command in this recess PHP framework tutorial. What I don't understand is how is PHP supposed to interpret my POST, it always comes up as an empty array.

curl -i -X POST -d '{"screencast":{"subject":"tools"}}'  \       http://localhost:3570/index.php/trainingServer/screencast.json 

(The slash in there is just to make me not look like an idiot, but I executed this from windows using PHP 5.2, also tried on a Linux server, same version with Linux curl)

There must be something I'm missing because it seems pretty straightforward, the post just isn't be interpreted right, if it was, everything would work great.

This is what I get back:

 HTTP/1.1 409 Conflict Date: Fri, 01 May 2009 22:03:00 GMT Server: Apache/2.2.8 (Win32) PHP/5.2.6 X-Powered-By: PHP/5.2.6 Transfer-Encoding: chunked Content-Type: text/html; charset=iso-8859-1  {"screencast":{"id":null,"subject":null,"body":null,          "dataUrl":null,"dataMedium":null,"createdOn":null,"author":null}} 
like image 371
Peter Turner Avatar asked May 01 '09 22:05

Peter Turner


People also ask

How pass JSON data in Curl POST?

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.

How get POST JSON in PHP?

To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.

Can I use Curl in PHP?

cURL is a PHP extension that allows you to use the URL syntax to receive and submit data. cURL makes it simple to connect between various websites and domains.


2 Answers

Normally the parameter -d is interpreted as form-encoded. You need the -H parameter:

curl -v -H "Content-Type: application/json" -X POST -d '{"screencast":{"subject":"tools"}}' \ http://localhost:3570/index.php/trainingServer/screencast.json 
like image 71
Jim Carrig Avatar answered Oct 10 '22 05:10

Jim Carrig


Jordans analysis of why the $_POST-array isn't populated is correct. However, you can use

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

to just retrieve the http body and handle it yourself. See PHP input/output streams.

From a protocol perspective this is actually more correct, since you're not really processing http multipart form data anyway. Also, use application/json as content-type when posting your request.

like image 34
Emil H Avatar answered Oct 10 '22 07:10

Emil H