How can PHP developers ensure secure communication over HTTPS and handle TLS protocol versions in their code?

To ensure secure communication over HTTPS and handle TLS protocol versions in PHP code, developers can set the appropriate SSL/TLS context options when making requests using cURL. This includes specifying the minimum and maximum TLS versions to use, as well as verifying the SSL certificate of the server to prevent man-in-the-middle attacks.

$url = 'https://example.com/api';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CAINFO, '/path/to/cacert.pem');
curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
$response = curl_exec($ch);

if(curl_errno($ch)){
    echo 'Curl error: ' . curl_error($ch);
}

curl_close($ch);

// Handle the response data
echo $response;