note 54150 deleted from ref.curl by danbrown
| From: | danbrown@php.net | Date: | Sun, 17 May 2009 19:37:31 +0000 |
| Subject: | note 54150 deleted from ref.curl by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-155245@lists.php.net to get a copy of this message | ||
Note Submitter: eric at harmonylinemusic dot com
----
After trying both ksavage and mmm's attempts to send HTTP POST's with full xml in them, I
was finally successful after using an obscure content-type (multipart/mixed) with a boundary
declaration. Incidentally, CURLOPT_CUSTOMREQUEST only accepts method names like 'POST' or
'PUT', not entire headers. You need to use CURLOPT_HTTPHEADER.
<?php
$request = "<xml>...</xml>";
$header[] = "Host: $host";
$header[] = "MIME-Version: 1.0";
$header[] = "Content-type: multipart/mixed; boundary=----doc";
$header[] = "Accept: text/xml";
$header[] = "Content-length: ".strlen($request);
$header[] = "Cache-Control: no-cache";
$header[] = "Connection: close \r\n";
$header[] = $request;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 4);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST,'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
?>
On the other side, the server grabs the post data and strips the boundaries.
<?php
$somecontent = $HTTP_RAW_POST_DATA;
$somecontent = trim(str_replace('----doc','',$somecontent));
echo $somecontent;
//returns <xml>...</xml>
?>
Back at the client, the server's output is taken by curl_exec() and stored in $data
<?php
$data = curl_exec($ch);
if (curl_errno($ch)) {
print curl_error($ch);
} else {
curl_close($ch);
echo $data;
//returns <xml>...</xml>
}
?>
Compared to SOAP or REST, this is really an enormous pain, plus the server still has to parse the
xml to be able to use it. But sometimes it's unavoidable. Enjoy.
Eric