How to solve the problem of curl returning false in php? (example explanation)

不言
Release: 2023-04-04 16:24:01
forward
3238 people have browsed it

This article introduces the solutions to the problems I encountered when using curl. Hope it helps everyone.

First let’s look at an encapsulated curl function

function request_post($url = '', $param = '') {
    if (empty($url) || empty($param)) {
        return false;
    }
    $postUrl = $url;
    $curlPost = $param;
    $curl = curl_init();//初始化curl
    curl_setopt($curl, CURLOPT_URL,$postUrl);//抓取指定网页
    curl_setopt($curl, CURLOPT_HEADER, 0);//设置header
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    curl_setopt($curl, CURLOPT_POST, 1);//post提交方式
    curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);//提交的参数
    $data = curl_exec($curl);//运行curl
    curl_close($curl);
    
    return $data;
}
Copy after login

When called, the return result is bool(false)
We are in the curl_exec function The error obtained earlier through curl_error($curl) is also string(0) "" empty string.

Finally I found that the interface address of the API I called was ssl protocol, and then just add the following two

curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
Copy after login

Ifcurl If the requested address contains spaces, false will also be returned. Pay special attention to this.

I have also encountered one before that returns falseprintcurl_error( $curl)What I get is the following error

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

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

//CURL_HTTP_VERSION_1_0 (强制使用 HTTP/1.0)
//CURL_HTTP_VERSION_1_1 (强制使用 HTTP/1.1)。
curl_setopt($curlp, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
Copy after login

The above is the detailed content of How to solve the problem of curl returning false in php? (example explanation). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!