0

I am writing PHP code to send XML string data to a site using HTTP post with the encType: multipart/form-data encoding. I am thinking of using PHP's http_post_data function. Before sending the data, I believe I need to encode it, but I cannot see a PHP function to do this for me, nor do I know how to write such a function myself.

This is what I have so far (but http_request_body_encode() is certainly not the correct function):

$options = array('headers' => array('Content-Type' => 'multipart/form-data'));
$fields = array('operation' =>'doMDUpload', 'login_id' => $doi_username, 'login_passwd' => $doi_password, 
  'area' => ($debug ? "test" : "live"), 'fname' => $writer->outputMemory());
$info = array();
$response = http_post_data($crossref_deposit_url, http_request_body_encode($fields, array()), $options, $info);

$writer->outputMemory is an XML string containing bibliometric data.

Nigel
  • 585
  • 1
  • 5
  • 20

1 Answers1

2

Well, http_request_body_encode() would be the correct function. But it is not a core function. It's available with the http pecl extension, that's not even installed per default on PHP 5.3.

It also does not generate a multipart/form-data per default (instead x-www-form-urlencode). You can trick it by supplying a fake $files array however:

print http_request_body_encode(array("field"=>123), array(NULL=>NULL));

Now the second problem is that you need to cut out the first line. That's the Content-Type with the correct boundary= attribute. And that seems fiddly to me.

So better use the HttpRequest class directly, and let it handle the POST encoding and sending at once. Alternatively use the PEAR or Zend class, which also work regardless of presence of the HTTP extension module.

mario
  • 144,265
  • 20
  • 237
  • 291
  • Thank you for your very helpful answer, but it leaves me with a couple of points I don't quite understand: – Nigel Feb 20 '11 at 14:39
  • Thank you for your very helpful answer, but it leaves me with a couple of points I don't quite understand: (1) "you need to cut out the first line. That's the Content-Type with the correct boundary= attribute." Why do I need to do that? Shouldn't I rather remove my code (line 1 of the code in my question) that sets a header? (2) If I were to use the HttpRequest class directly, how do I tell it to use multipart/form-data encoding? – Nigel Feb 20 '11 at 14:46
  • @micrology: You must cut out the content-type line because it would otherwise be the wrong format. The header line must be part of the headers, not content body. I don't know how to force multipart/, maybe with the same $files trick on ::setPostFiles. – mario Feb 20 '11 at 16:40