Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post JSON using Curl

Tags:

json

post

php

curl

I am receiving a JSON which I can receive using php://input and I need to post it back to a different URL, but I'm not sure how to format it. Here's how I receive it:

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

I could json_decode it and then parse out the array so that it would fit a normal POST-like request such as hello=world&stack=overflow etc. But is it possible to pass the JSON just into a curl post like this:

curl_setopt($curl_handle, CURLOPT_POST, 1);
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $updates);

and then the client could just php://input to grab the data again? The reason I ask is because the client says he is not receiving the data, it may be he doesn't have it set up correctly. I've noticed when you do something like this through a command line you have to include -H in the command so that the data is interpretted as normal POST, perhaps there's a libcurl CURLOPT I need to set?

Thanks!

like image 385
Doug Molineux Avatar asked Aug 18 '10 16:08

Doug Molineux


People also ask

How do I POST JSON with Curl?

Curl POST JSON data. 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 do you POST data using Curl?

How to post form data using Curl? If you want to post form data with Curl, you can use the -F (--form) or -d (--data) command-line parameters. With the -F command-line parameter, form data is sent as "multipart/form-data", and with the -d command-line parameter, form data is sent as "application/x-www-form-urlencoded".

Does Curl use JSON?

curl will not touch or parse the data that it sends, so you need to make sure it is valid JSON yourself. You can use multiple --json options on the same command line. This makes curl concatenate the contents from the options and send all data in one go to the server.


1 Answers

Well folks, I have figured this one out!

To send a post as a different content-type (ie.. application/json or text/xml) add this setopt call

curl_setopt($ch, CURLOPT_HTTPHEADERS,array('Content-Type: application/json'));

like image 191
Doug Molineux Avatar answered Sep 27 '22 02:09

Doug Molineux