19

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.

3
  • 5
    Try to use HTTP1.1: curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); Commented Jul 3, 2019 at 7:55
  • Have you checked whether the API documentation contains some examples? Maybe you are using the API in a wrong way altogether Commented Jul 3, 2019 at 8:14
  • @CodyKL : Implemented your solution in my code, keeping it under observation for few days. will be back with my feedback in 2 to 3 days. Commented Jul 4, 2019 at 5:10

1 Answer 1

36

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Solution for you CLI folks out there: v7.33.0 or newer has the --http1.1 switch for you :)
Wow. How many thousands or millions of scripts do you think they broke with that decision? Why not have a flag to use http2 and leave the default as-is? Sigh...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.