Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I send raw POST data with cURL? (PHP)

Tags:

post

php

curl

I'm attempting to send raw POST data to a page using $HTTP_RAW_POST_DATA, but my attempts failed and an undefined index notice was given.

I have attempted the following:

curl_setopt($handle, CURLOPT_POSTFIELDS, 'Raw POST data');   // Doesn't seem to work at all.
curl_setopt($handle, CURLOPT_POSTFIELDS, array('Raw POST data'));   // 0 => Raw POST data

I did some research and some people had suggested sending a header (Content-Type: text/plain) in the request, which didn't seem to affect anything.

Is there a solution for this issue?

like image 711
user1488335 Avatar asked Oct 27 '12 10:10

user1488335


1 Answers

You get an error in the response part of your sender/receiver cycle.

While this might very well be a problem of the sender (which does not send a proper request), it may also be caused by a misconfiguration in the receiving PHP script. To wit, even if the request is correct, the receiver might nonetheless not have HTTP_RAW_POST_DATA available.

See: http://www.php.net/manual/en/ini.core.php#ini.always-populate-raw-post-data

Always populate the $HTTP_RAW_POST_DATA containing the raw POST data. Otherwise, the variable is populated only with unrecognized MIME type of the data. However, the preferred method for accessing the raw POST data is php://input. $HTTP_RAW_POST_DATA is not available with enctype="multipart/form-data".

So the first thing to check is whether $HTTP_RAW_POST_DATA is indeed populated, which from the page above requires either:

  1. the .ini variable always_populate_raw_post_data is True,
  2. or the POST is sent with a Content-Type that the POST handler does not recognize (maybe one could use "text/raw")

At this point, the correct way of sending data would be

curl_setopt($handle, CURLOPT_POSTFIELDS, urlencode('Raw POST data'));

However, note that the recommended way of receiving those data would be not to rely on $HTTP_RAW_POST_DATA at all, but to read the contents of the virtual file php://input.

php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data.

like image 94
LSerni Avatar answered Sep 24 '22 17:09

LSerni