我正在构建一个脚本来检查网站是否使用 SSL。例如,我们使用“http://www.google.com/”,它将被重定向到“https://www.google.com/”。我该如何检查?我正在使用以下 cURL 代码来获取网站的 header 。
<?php
$url = 'https://www.google.com';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url); // set url
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6"); // set browser/user agent
curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header'); // get header
curl_exec($ch);
function read_header($ch, $string) {
print "Received header: $string";
return strlen($string);
}
?>
输出:
HTTP/1.1 302 Found
Cache-Control: private
Content-Type: text/html; charset=UTF-8
Location: https://www.google.co.in/?gfe_rd=cr&ei=YEAkV7SEFrTv8wexyy0
Content-Length: 259
Date: Sat, 30 Apr 2016 05:19:28 GMT
Alternate-Protocol: 443:quic
Alt-Svc: quic=":443"; ma=2592000; v="33,32,31,30,29,28,27,26,25"
最佳答案
PHP - cURL
我认为使用 cURL 有点矫枉过正,但不管怎样,你可以开始了。
<?php
function ignoreHeader( $curl, $headerStr ) {
return strlen( $headerStr );
}
$curl = curl_init( "https://example.com/" );
curl_setopt( $curl, CURLOPT_NOBODY, TRUE );
curl_setopt( $curl, CURL_HEADERFUNCTION, 'ignoreHeader' );
curl_exec( $curl );
$result = false;
if ( curl_errno($curl) == 0 ) {
$info = curl_getinfo( $curl );
if ( $info['http_code'] == 200 ) {
$result = true;
}
}
?>
PHP - 没有 cURL
如果你想检查一个网站是否有 SSL 证书。您可以只打开一个流并检查 SSL 证书参数。
<?php
// Create a stream context
$stream = stream_context_create ( array( "ssl" => array( "capture_peer_cert" => true ) ) );
// Bind the resource 'https://www.example.com' to $stream
$read = fopen( "https://www.example.com", "rb", false, $stream );
// Get stream parameters
$params = stream_context_get_params( $read );
// Check that SSL certificate is not null
// $cert should be for example "resource(4) of type (OpenSSL X.509)"
$cert = $params["options"]["ssl"]["peer_certificate"];
$result = ( !is_null( $cert ) ) ? true : false;
?>
如果要检查主机是否接受 443 端口上的连接,可以使用 fsockopen
发起与主机的套接字连接。
<?php
// Set host and port.
$host = 'example.com';
$port = 443;
// Initiate a socket connection with 'example.com' and check the result.
$fp = fsockopen('ssl://'. $host, $port, $errno, $errstr, 30);
$result = ( !is_null( $fp ) ) ? true : false;
?>
关于php - 使用 CURL 检查网站是否使用 SSL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36950874/