tags:

views:

2369

answers:

2

How can I do a RAW POST in PHP using curl. Raw post as in without any encoding, and my data is stored in a string. The data should be formatted like this

... usual HTTP header ...
Content-Length: 1039
Content-Type: text/plain


89c5fdataasdhf kajshfd akjshfksa hfdkjsa falkjshfsa
ajshd fkjsahfd lkjsahflksahfdlkashfhsadkjfsalhfd
ajshdfhsafiahfiuwhflsf this is just data from a string
more data kjahfdhsakjfhsalkjfdhalksfd

One option is to manually write the entire HTTP header being sent, but that seems less optimal.

Any way I can just pass options to curl_setopt() that say use POST, use text/plain, and send the raw data from a $variable?

Thanks.

+7  A: 

I just found the solution, kind of answering to my own question in case anyone else stumbles upon it.

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,            "http://url/url/url" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST,           1 );
curl_setopt($ch, CURLOPT_POSTFIELDS,     "body goes here" ); 
curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: text/plain')); 

$result=curl_exec ($ch);
The Unknown
+1  A: 

Yes, you just need to pass a set of specific options to curl_setopt: namely:

But your POST data must be in key/value pair form, so even though you do have a chunk of data you want to POST just assign it to a dummy key that you can then retrieve from the server.

So assuming your data is in $variable:

$fields = array('data' => $variable);
curl_setopt(CURLOPT_HTTPHEADER, array('Content-Type' => 'text/plain'));
curl_setopt(CURLOPT_POST, true);
curl_setopt(CURLOPT_POSTFIELDS, $variable);

And then call curl_exec as normal.

Cody Caughlan