Moving Curl client ssl to Guzzle

greggles picture greggles · Sep 19, 2014 · Viewed 9k times · Source

I'm using Guzzle v3.9.2 with both php 5.3 and php 5.5.

I have the following working curl code that uses an ssl client certificate:

$url = "https://example.com/";
$cert_file = '/path/to/certificate.pem';

$ch = curl_init();
$options = array(
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_URL => $url ,
  CURLOPT_SSLCERT => $cert_file ,
);

curl_setopt_array($ch , $options);
$output = curl_exec($ch);

if (!$output) {
  echo "Curl Error : " . curl_error($ch);
}
else {
  echo htmlentities($output);
}

I have tried to move it to Guzzle:

require '/var/www/vendor/autoload.php';
use Guzzle\Http\Client;
$client = new Client();
$request = $client->get($url, array('cert' => $cert_file));
$response = $client->send($request);
echo $response . PHP_EOL;
print 'HI' . PHP_EOL;

When I run it using curl I get a 200 response. When I use Guzzle I get a 403.

Answer

Pouya Darabi picture Pouya Darabi · Sep 22, 2014

try like this:

 $client = new Client();
 $response = $client->get($url, array(), array('cert' => $cert_file));

and for check add this line:

 $this->assertEquals($cert_file, $request->getCurlOptions()->get(CURLOPT_SSLCERT));

or use this:

 $client = new Client();
 $request = $client->createRequest('GET', $url);
 $request->getCurlOptions()->set(CURLOPT_SSLCERT, $cert_file);
 $response = $client->send($request);

if you use self singed certificate set this options :

$request->getCurlOptions()->set(CURLOPT_SSL_VERIFYHOST, false);
$request->getCurlOptions()->set(CURLOPT_SSL_VERIFYPEER, false);

set this line before send request :

$request = $client->get( .... )
.
.
.
$request->setResponse(new Response(200), true);
$request->send();

check your url and enter it compelete like this :

$url = 'https://example.com/index.php';

and you can add default options like your curl code :

$request->getCurlOptions()->set(CURLOPT_RETURNTRANSFER , true);
$request->getCurlOptions()->set(CURLOPT_FOLLOWLOCATION , true);