Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Curl error HTTP/2 stream 0 was not closed cleanly: PROTOCOL_ERROR (err 1)

Tags:

php

curl

I am trying to hit an API from one server to another and getting this response in curl_error($curl); HTTP/2 stream 0 was not closed cleanly: PROTOCOL_ERROR (err 1). Frequency of getting this error message is low, out of 10 attempts 1 to 2 times.

But why i am getting this error, is any specific reason that i am missing?

my Curl code is:

$data = http_build_query(array('param1' => 'test','status' => 'Success'));
$curl = curl_init(); 
curl_setopt($curl, CURLOPT_URL, "server api link");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec($curl);
if (curl_error($curl)) {
    $error_msg = curl_error($curl);
}

print_r($error_msg);
curl_close($curl);

Query is same as asked at this link curl php HTTP/2 stream 0 was not closed cleanly

Asking it again as no solution found in previous link, even not at any other locations.

like image 441
Akhilesh Kumar Avatar asked Jul 03 '19 07:07

Akhilesh Kumar


Video Answer


1 Answers

I ran into this exact same issue and the comment from @CodyKL actually solved it in my case so I figured I would turn it into an answer for others to refer to.

Short answer:

Add the following line to your curl request and all shall be solved

curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);

Slightly Longer Answer:

Since curl 7.62.0 the default option is: CURL_HTTP_VERSION_2TLS

Before that the default used to be: CURL_HTTP_VERSION_1_1

Some older APIs etc. don't appear to be compatible with the latest HTTP version. The newer version of CURL will use this protocol by default and as a result will fail. This can cause some rather confusing behaviour because a script that works on one machine may not necessarily work on another. To maximise compatibility you should ideally specify CURLOPT_HTTP_VERSION for curl requests to older servers which don't support CURL_HTTP_VERSION_2TLS.

like image 150
Henry Howeson Avatar answered Oct 12 '22 03:10

Henry Howeson