nicholasnet nicholasnet - 4 months ago 114
PHP Question

Convert cURL request to Guzzle PHP

I am trying to convert existing cURL request to Guzzle 6. This is the cURL request. The code for curl request is like this.

$xml = file_get_content('new.xml');

// Initialize handle and set options
$ch = curl_init();

curl_setopt( $ch, CURLOPT_URL, $this->xml_post_url );//
curl_setopt( $ch, CURLOPT_SSLCERT, $this->sslcert );//
curl_setopt( $ch, CURLOPT_SSLKEY, $this->sslkey );//
curl_setopt( $ch, CURLOPT_POSTFIELDS, $raw_request );
curl_setopt( $ch, CURLOPT_TIMEOUT, 30 );
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 20 );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Connection: close') );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt( $ch, CURLOPT_SSLCERTPASSWD, $this->sslcertpasswd );
curl_setopt( $ch, CURLOPT_SSLKEYPASSWD, $this->sslkeypasswd );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); // capture the response to a string

// give it 3 tries
for ($i=1; $i<=3; ++$i) {

$raw_response = curl_exec($ch);
$response_HTTP_CODE = (int) curl_getinfo( $ch, CURLINFO_HTTP_CODE );

if (200 <= $response_HTTP_CODE and $response_HTTP_CODE < 400) {

if ($raw_response !== false) {

curl_close( $ch );
return $raw_response;

}

}
elseif (500 <= $response_HTTP_CODE and strlen( $raw_response ) > 0) {

$offset = strpos( $raw_response, '<errortext>');

if ($offset !== false) {

curl_close( $ch );
break;

}
}

sleep( 1 ); // give it a moment
}

curl_close( $ch );


Is there anyway to convert this into Guzzle request in sane way with retry option as well if possible.

This is what I tried

$request = $this->getClient()->post($this->request['endPointUrl'], [
'body' => $xml,
'cert' => $this->request['sslCert'],
'config' => [
'curl' => [
CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => true
]
]
]);
$response = $request->send()->xml();


But I am getting cURL exception.

Answer

Alright finally I resolved this issue. I am posting my solution with a hope that it might help someone.

$client = new Client();
$client->setDefaultOption('verify', false);

$response = $client->post($endPointUrl, [
                'body'    => ['file_filed' => $xml],
                'cookies' => true,
                'cert'    => [$sslCert, $sslCertPassword],
                'ssl_key' => [$sslKey, $sslKeyPassword]
            ]);

if (200 === $response->getStatusCode()) {

    $xmlResponse = $response->xml();

} else {

    // do something with error.

}

For retry I used Guzzle retry subscriber