Reputation: 4996
I have a function in Zend Framework 2 which sends CURL requests
to an API and return results like below :
use Zend\Http\Client as HttpClient;
public function curl($url, array $params, $method = "POST"){
$client = new HttpClient();
$client->setAdapter('Zend\Http\Client\Adapter\Curl');
$client->setUri($url);
$client->setOptions(array(
'maxredirects' => 0,
'timeout' => 30
));
$client->setMethod($method);
$client->setHeaders(array(
'username: xxxxxxx',
'password: xxxxxxx',
));
//if(!empty($params)) {
if ($method == "POST" || $method == "PUT") {
$client->setParameterPOST($params);
} else {
$client->setParameterGET($params);
}
//}
$response = $client->send();
return $response;
}
and calling it as :
$response = $this->api->curl($api_url, array('paramName' => "value"), "DELETE");
But it is unable to send parameter along with the request and API returning 500 internal server error with Exception.
Upvotes: 0
Views: 2537
Reputation: 4996
To get this done please update file Zend\Http\Client\Adapter\Curl.php on line 396 please add another elseif statement :
elseif ($method == 'DELETE') {
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $body);
}
then it'll look like :
if ($method == 'POST') {
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $body);
} elseif ($curlMethod == CURLOPT_UPLOAD) {
// this covers a PUT by file-handle:
// Make the setting of this options explicit (rather than setting it through the loop following a bit lower)
// to group common functionality together.
curl_setopt($this->curl, CURLOPT_INFILE, $this->config['curloptions'][CURLOPT_INFILE]);
curl_setopt($this->curl, CURLOPT_INFILESIZE, $this->config['curloptions'][CURLOPT_INFILESIZE]);
unset($this->config['curloptions'][CURLOPT_INFILE]);
unset($this->config['curloptions'][CURLOPT_INFILESIZE]);
} elseif ($method == 'PUT') {
// This is a PUT by a setRawData string, not by file-handle
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $body);
} elseif ($method == 'PATCH') {
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $body);
} elseif ($method == 'DELETE') {
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $body);
}
and then update the if statement of your function :
if ($method == "POST" || $method == "PUT" || $method == "DELETE") {
$client->setParameterPOST($params);
} else {
$client->setParameterGET($params);
}
your function will look like :
public function curl($url, array $params, $method = "POST") {
$client = new HttpClient();
$client->setAdapter('Zend\Http\Client\Adapter\Curl');
$client->setUri($url);
$client->setOptions(array(
'maxredirects' => 0,
'timeout' => 30
));
$client->setMethod($method);
$client->setHeaders(array(
'username: xxxxxxx',
'password: xxxxxxx',
));
//if(!empty($params)) {
if ($method == "POST" || $method == "PUT" || $method == "DELETE") {
$client->setParameterPOST($params);
} else {
$client->setParameterGET($params);
}
//}
$response = $client->send();
return $response;
}
It worked for me..!!
Upvotes: 1