我有一个代码可以检查网站是否有SSL证书,如下所示:
$url = "stackoverflow.com";
$orignal_parse = parse_url($url, PHP_URL_HOST);
$get = stream_context_create(array("ssl" => array("capture_peer_cert" => TRUE)));
$read = stream_socket_client("ssl://".$orignal_parse.":443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $get);
$cert = stream_context_get_params($read);
$certinfo = openssl_x509_parse($cert['options']['ssl']['peer_certificate']);
var_dump($certinfo);
如果我插入包含HTTPS的网址,此代码会向我返回有关该证书的所有信息,但如果我插入的网址不包含HTTPS,则会收到以下错误:
警告:stream_socket_client():无法连接到ssl://:443 (因为目标机器是主动的,所以无法建立连接 拒绝了。)在
我如何解决这个问题?
答案 0 :(得分:1)
您应该检查stream_socket_client()
的返回值,如果它返回false则不再继续(因为资源无效)。
$url = "stackoverflow.com";
$orignal_parse = parse_url($url, PHP_URL_HOST);
$get = stream_context_create(array("ssl" => array("capture_peer_cert" => TRUE)));
$read = stream_socket_client("ssl://".$orignal_parse.":443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $get);
if (!$read) {
// ssl connection failed for some reason
// could be a certificate error or failure to connect on port 443
echo "Failed to connect to site. Error {$errno}: {$errstr}\n";
} else {
$cert = stream_context_get_params($read);
$certinfo = openssl_x509_parse($cert['options']['ssl']['peer_certificate']);
var_dump($certinfo);
}