3

I've found that if I try a PHP POST curl, the postvars are sent fine. Once I add the httpheader of content-type: application/json the postvars don't go across any more. I've tried the postvars as a JSON string and as a query string.

Showing some code:

$ch = curl_init();

$post =  json_encode(array('p1' => 'blahblahblah', 'p2' => json_encode(array(4,5,6))));

$arr = array();
array_push($arr, 'Content-Type: application/json; charset=utf-8');

curl_setopt($ch, CURLOPT_HTTPHEADER, $arr);
curl_setopt($ch, CURLOPT_URL, 'https://example.com/file.php');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

curl_exec($ch);
curl_close($ch);
halfer
  • 19,824
  • 17
  • 99
  • 186
Jacksonkr
  • 31,583
  • 39
  • 180
  • 284

1 Answers1

5

A real HTTP Post, that gets broken into an array automagically by PHP must be formatted in name=value pairs, the best way to do this in PHP is using the http_build_query function.

http://ca2.php.net/manual/en/function.http-build-query.php

There is an example that works in the PHP Manual using curl:

http://ca2.php.net/manual/en/function.curl-exec.php#98628

What you're doing is a 'RAW' post, see this other question:

How to post JSON to PHP with curl

A quick snippet to get the RAW Json data.

<?php

print_r(json_decode(file_get_contents('php://input')));
Community
  • 1
  • 1
therealjeffg
  • 5,790
  • 1
  • 23
  • 24
  • What I didn't mention at the beginning, which I should have (hindsight is 20/20) is that I don't control the page I'm posting too. It's actually a .net tool I'm posting too and it's mad that their is no post info coming through. Posting with jQuery works just fine with simulating exactly what I'm doing. I'm merely curling because of cross-domain issues. PHP Curl breaks when I introduce CURLOPT_HTTPHEADER which I have to specify the content-type or the server I'm talking to boots me. Perplexed. – Jacksonkr Feb 17 '11 at 16:12
  • The POST variables go through, but as soon as I set the content-type to application/json they quit. what is that all about!? – Jacksonkr Feb 17 '11 at 16:22
  • Well, not knowing how the .Net script works, it's hard to provide a solution. ;) It sounds actually like the script on the other end bails out is the content type isn't multi-part/form-data. – therealjeffg Feb 17 '11 at 20:02
  • It's a bummer because this works when using jQuery (XHR), but the curl doesn't work :( If I could just get curl to use a Content-Type of application/json and send the POST data as POSTDATA instead of RAW DATA then i'd be golden. I suppose this is one for the shelf. so sad. Thanks for your pro help. – Jacksonkr Feb 18 '11 at 00:27
  • PHP changes the POST vars to RAW post which means you need to use file_get_contents or equiv. This was the right answer (thanks @anuckistani), but since I'm working with a .net backend, I wasn't able to solve this :( – Jacksonkr Mar 01 '11 at 21:49