Solution for $_POST empty after drupal_http_request

The function drupal_http_request can be used to POST data to a URL. However, what the documentation does not mention is that when you invoke it without the Content-Type header, the receiver might not see any of the posted content.

Wrong:

  $result = drupal_http_request(
    url('some/url', array(absolute => TRUE)),
    array(),
    'POST',
    'param1=value1&param2=value2');

Correct:

  $result = drupal_http_request(
    url('some/url', array(absolute => TRUE)),
    array('Content-Type' => 'application/x-www-form-urlencoded'),
    'POST',
    'param1=value1&param2=value2');

7 comments:

Albert Albala said...

I spent hours trying to get POST to work until I found this post. I linked here from the API page at http://api.drupal.org/api/function/drupal_http_request/6.

mimrock said...

Thanks both of you!

Ayesh said...

....data to another Drupal script...
Can't we post to just any script ?

Thanks for the tip btw. Helps a LOT!

jpl said...

@Ayesh: Thanks - wording corrected. Technically, the original sentence wasn't false, but it afforded misinterpretations.

Anonymous said...

For Drupal 7, the $options array needs to contain an element 'header' which is itself an array of headers in which you put in Content-Type.

Anonymous said...

Thanks for your post! finally I could solve the problem..

Tomek said...

Thanks for the tip btw. Helps a LOT!
You saved my day

Post a Comment