Explain the solution of returning false from curl in php in detail

  • 2021-12-04 09:41:52
  • OfStack

First, look at a encapsulated curl function


function request_post($url = '', $param = '') {
 if (empty($url) || empty($param)) {
 return false;
 }
 $postUrl = $url;
 $curlPost = $param;
 $curl = curl_init();// Initialization curl
 curl_setopt($curl, CURLOPT_URL,$postUrl);// Crawl the specified web page 
 curl_setopt($curl, CURLOPT_HEADER, 0);// Settings header
 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);// Require the result to be a string and output to the screen 
 curl_setopt($curl, CURLOPT_POST, 1);//post Submission method 
 curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);// Submitted parameters 
 $data = curl_exec($curl);// Run curl
 curl_close($curl);
 
 return $data;
}

When called, the result returned is bool(false)

We're in curl_exec Function is preceded by the curl_error($curl) Getting errors is also string(0) "" Empty string.

Finally, I found that the interface address of api I called was ssl Agreement, and then add the following two.


curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

If curl If the requested address contains a space, it will also be returned false Yes, this one should also pay special attention.

I have encountered 1 return before false Print curl_error($curl) What you get is the following error


string(39) "Problem (2) in the Chunked-Encoded data" bool(false)

The solution to this error is to set the HTTP protocol version used by curl by adding the following sentence


//CURL_HTTP_VERSION_1_0 ( Mandatory use  HTTP/1.0)
//CURL_HTTP_VERSION_1_1 ( Mandatory use  HTTP/1.1) . 
curl_setopt($curlp, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);

Related articles: