简体   繁体   English

PHP套接字无法连接到ssl // :: 443

[英]php sockets unable to connect to ssl//:443

I have a code that checks if a website have SSL certificate as you can see below: 我有一个代码可以检查网站是否具有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);

If I insert a url that contains HTTPS, this code return to me all the information about the certificate, but if I insert a url that doesn't contain HTTPS I receive the following error: 如果我插入一个包含HTTPS的URL,此代码将向我返回有关证书的所有信息,但是如果我插入一个不包含HTTPS的URL,则会收到以下错误:

Warning: stream_socket_client (): Unable to connect to ssl: //: 443 (No connection could be made because the target machine actively refused it.) In 警告:stream_socket_client():无法连接到ssl://:443(无法建立连接,因为目标计算机主动拒绝了它。)

How I can solve this problem? 我该如何解决这个问题?

You should be checking the return value of stream_socket_client() and if it returns false not proceeding any further (because the resource is not valid). 您应该检查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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM