phpcertificateguzzle

Passing multiple certificates through Curl request using Guzzle


I have an http request that uses a key, certificate, and certificate chain. How can it be translated to Guzzle? The problem is that I do not know how to add all my certificates to the Guzzle request. In the documentation there is an example for only one certificate

Example of my request:

// curl -vvv -X POST --header 'Content-Type: application/x-www-form-urlencoded' --header 'Accept: application/json' --cacert client-bundle.pem --key key.pem --cert cert.pem 'my_url'

My function is sending a request using Guzzle at the moment:

try {
$response = $this->request('POST', 'my_url', [
                'headers' => [
                    'Content-Type' => 'application/x-www-form-urlencoded',
                    'Accept' => 'application/json'
                ],

            ]);

return Json::decode($response->getBody()->getContents());
            $this->checkResponse($result);

        } catch (GuzzleException $e) {
            return $e->getMessage();
}

I tried to find an example of sending a request with the transfer of several certificates. I could not find such an example, using only one certificate does not suit me


Solution

  • To add multiple certificates to a Guzzle request, you can use the ssl_key and cert options in the request options array. The ssl_key option can be set to the path of your private key file, and the cert option can be set to the path of your certificate file.

    $certFile = 'cert.pem';
    $keyFile = 'key.pem';
    $caFile = 'client-bundle.pem';
    
    $client = new GuzzleHttp\Client();
    
    try {
        $response = $client->request('POST', 'my_url', [
            'headers' => [
                'Content-Type' => 'application/x-www-form-urlencoded',
                'Accept' => 'application/json'
            ],
            'cert' => [$certFile, $keyFile],
            'ssl_key' => $keyFile,
            'verify' => $caFile
        ]);
    
        $result = $response->getBody()->getContents();
    
        $this->checkResponse($result);
    
        return Json::decode($result);
    
    } catch (GuzzleHttp\Exception\GuzzleException $e) {
        return $e->getMessage();
    }