PHP Get SSL Certificate Chain



<?php
$hostname = "login.yahoo.com";
$ssloptions = array(
    "capture_peer_cert_chain" => true, 
    "allow_self_signed"=>false, 
    "CN_match"=>$hostname, 
    "verify_peer"=>true, 
    "SNI_enabled"=>true,
    "SNI_server_name"=>$hostname,
    "cafile"=>'/etc/ssl/certs/ca-certificates.crt' //mozilla ca cert bundle: http://curl.haxx.se/docs/caextract.html
);
 
$ctx = stream_context_create( array("ssl" => $ssloptions) );
$result = stream_socket_client("ssl://$hostname:443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $ctx);
$cont = stream_context_get_params($result);
foreach($cont["options"]["ssl"]["peer_certificate_chain"] as $cert)
{
    openssl_x509_export($cert, $pem_encoded);
    echo $pem_encoded;
}
?>

output:
-----BEGIN CERTIFICATE-----
MIIGyTCCBbGgAwIBAgIQA6HgoNmVm1KwxXVHg5jZHzANBgkqhkiG9w0BAQUFADBm
MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
d3cuZGlnaWNlcnQuY29tMSUwIwYDVQQDExxEaWdpQ2VydCBIaWdoIEFzc3VyYW5j
ZSBDQS0zMB4XDTEyMDMxMDAwMDAwMFoXDTE0MDMxNDEyMDAwMFowXjELMAkGA1UE
BhMCVVMxCzAJBgNVBAgTAkNBMRIwEAYDVQQHEwlTdW5ueXZhbGUxFDASBgNVBAoM
C1lhaG9vISBJbmMuMRgwFgYDVQQDEw9sb2dpbi55YWhvby5jb20wggEiMA0GCSqG
SIb3DQEBAQUAA4IBDwAwggEKAoIBAQCwXnRevccv4D0M0Zw3geFFOi6dWSU4ZCv7
i90ilGzy6PGsEEHolHQHR2Vb39rqf8RfxOP/WDPG6HLtHNm8YZoc0ldbtmGIbRtP
lD738XvxToTUJNW85b9YRWXceeGigh03kISnbASpgIr9kxjDEUe+AliLdeweEtTA
wqsY/YNR84Ux9LZNOIFp4XHC7S/hCLkcixQ7CzGRiDNfqsKhGqKuYVggNbehIg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