php curl implements the complete code of ssl/tls ca.crt, client.crtm, client.key

Recently, I was docking an interface. Since the data involves user privacy, the interface uses ssl/tls encryption.
The other party directly sent me three files ca.crt, client.crt, client.key, I first Baidu, and I didn’t use crt's curl https request. After reading the manual, I found that it said that the crt file needs to be converted to pem. The file is fine. So I ran openssl on the online server and successfully converted. Then there is the request configuration of curl,

public function curl_verify_get($url)
    {
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        $header = array(
            'Accept: application/json',
            'Content-Type: application/json',
        );
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书,不是CA机构颁布的也没关系
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 检查证书中是否设置域名,如果不想验证也可设为0
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_FRESH_CONNECT, 1);//强制获取一个新的连接,替代缓存中的连接。
        curl_setopt($curl, CURLOPT_FORBID_REUSE, 1);//在完成交互以后强迫断开连接,不能重用。
        curl_setopt($curl, CURLOPT_CAINFO, __DIR__ . "ssl/ca.crt"); //ca文件路径,这里我用常量代替
        curl_setopt($curl, CURLOPT_SSLCERT, __DIR__ . "ssl/client.pem"); //client证书位置
        curl_setopt($curl, CURLOPT_SSLKEY, __DIR__ . "ssl/mycert.pem"); //client.key文件路径
        $data = curl_exec($curl);
        if (curl_error($curl)) {
            print "Error: " . curl_error($curl);
        } else {
            // 打印返回的内容
            curl_close($curl);
            return $data;
        }
    }

After working for a whole day, I finally finished it. I successfully got the data. I sorted out the logic.
1. The curl of php can't directly use the crt format certificate. First, convert the crt file to pem.
2. Configure CURLOPT_CAINFO, CURLOPT_SSLCERT, CURLOPT_SSLKEY.
That's it.

Guess you like

Origin blog.csdn.net/weixin_42094764/article/details/109247136