如何在cURL PHP中使用TLS 1.2

时间:2019-05-19 01:26:29  来源:igfitidea点击:

大多数Web/API服务提供商正在将其环境转移到TLS 1.2或更高版本。因此,要通过PHP应用程序使用它们的服务,还需要在建立连接时强制应用程序使用TLS 1.2。本教程将了解如何在phpccurl中使用TLS 1.2。

我们可以将以下代码添加到curl请求中以使用TLS 1.2。使用6作为CURLOPT_SSLVERSION forces cURL的值以使用TLS 1.2。

curl_setopt ($ch, CURLOPT_SSLVERSION, 6);

下面是我们上一个教程中使用cURL和PHP提交JSON数据的示例脚本。

<?php 
$data = array(
    'username' => 'adminoi',
    'password' => '012345678'
);
 
$payload = json_encode($data);

$ch = curl_init('https://api.example.com/api/1.0/user/login');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);

curl_setopt ($ch, CURLOPT_SSLVERSION, 6);  //强制请求使用TLS 1.2
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
 

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($payload))
);
 
$result = curl_exec($ch);
curl_close($ch);
?>