Quantcast
Channel: Franz's Web Blog
Viewing all articles
Browse latest Browse all 26

How to use ZF2's Curl Http Adapter with Header information

$
0
0
Just sharing some of my painful WTF experiences using ZF2's Curl Http client adapter so you wont have to deal with my headaches.

Basically I am trying to send a CURL_HTTPHEADER with these params.
This is what it should look like straight php:

$c = curl_init('http://url');
curl_setopt($c, CURLOPT_POST, 1);
curl_setopt($c, CURLOPT_POSTFIELDS, $data);
curl_setopt($c, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'Authorization: Bearer 1jo41324knj23o'
));
Simple enough right? Well I was assuming the same thing using ZF2's Curl Adapter:
$client = new Client('http://url');
$client->setMethod('post');

$adapter = new Curl()
$adapter->setCurlOption(CURLOPT_POST, 1);
$adapter->setCurlOption(CURLOPT_POSTFIELDS, $data);
$adapter->setCurlOption(CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'Authorization: Bearer 1jo41324knj23o'
));
Well the thing is this will not work because the headers and data are being set exclusively by write() in the client object as you will see in the source:

// inside Curl::write()
// line 374 Curl.php
curl_setopt($this->curl, CURLOPT_HTTPHEADER, $curlHeaders);

// line 380 Curl.php
if ($method == 'POST') {
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $body);
}

// line 398 Curl.php
if (isset($this->config['curloptions'])) ...
foreach ((array) $this->config['curloptions'] as $k => $v) ...

Notice at line 398 that this is where the remaining curl parameters gets set. This means that CURLOPT_HTTPHEADER and CURLOPT_POSTFIELDS have already been defined so our usage from above will not work (Maybe there is a CURL flag to overwrite this, I just don't know at the moment). So how do you make this work? You have to pass your definitions in the Client object:

$client = new Client('http://url');
$client->setMethod('post');
$client->setRawBody($data);
$client->setHeaders(array(
'Content-Type: application/json',
'Authorization: Bearer 1jo41324knj23o',
));
$client->setAdapter(new Curl());
$client->send();
Now the write() method will pull from these params when assembled

Viewing all articles
Browse latest Browse all 26

Trending Articles