Search code examples
phpauthenticationcurlclient-certificates

Curl error with client certificate authentication


I have to call an api that requires the client certificate authentication. I test this api in postman with client certification and its working perfectly. Now i want to do it with php curl. I tried below code but its giving me following error.

HTTP/2 stream 0 was not closed cleanly: HTTP_1_1_REQUIRED (err 13)

$url = 'https://someurl';
$json = 'somejson';




$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_VERBOSE, 1); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true); 
curl_setopt($ch, CURLOPT_SSLCERT, __DIR__."/certificate.pem"); 
curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM'); 
curl_setopt($ch, CURLOPT_SSLKEY, __DIR__."/privatekey.key"); 
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$responseData = curl_exec($ch);
if(curl_errno($ch)) {

    echo curl_error($ch);
}
curl_close($ch);

Solution

  • The error message has all the clues you need: HTTP_1_1_REQUIRED

    TLS client certificates are not supported for HTTP/2, so you need to make sure your curl request is done using HTTP/1.1 by explicitly asking for that. curl will by default upgrade to HTTP/2 on HTTPS URLs otherwise.

    Set CURLOPT_HTTP_VERSION to CURL_HTTP_VERSION_1_1.