我正在使用类似的代码
<?php
$url = 'http://www.example.com';
if(isset($_GET['url'])){$url = $_GET['url'];}
$array = get_headers($url);
$string = $array[0];
if(strpos($string,"200")){
echo 'url exists';
}
else{
echo 'url does not exist';
}
//this code does not works for ssl connection
?>
检查 URL 是否存在,但它不适用于使用 ssl 连接的网站,我的意思是 https://www.example.com类型站点
最佳答案
我不知道您是否可以将 get_headers
与 https 一起使用。
但作为替代方案(如果启用了 Curl),您可以使用以下函数:
function getheaders($url) {
$c = curl_init();
curl_setopt($c, CURLOPT_HEADER, true);
curl_setopt($c, CURLOPT_NOBODY, true);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($c, CURLOPT_SSL_VERIFYHOST, true);
curl_setopt($c, CURLOPT_URL, $url);
$headers = curl_exec($c);
curl_close($c);
return $headers;
}
如果您只需要 HTTP 状态代码,您可以像这样修改函数:
function getstatus($url) {
$c = curl_init();
curl_setopt($c, CURLOPT_HEADER, true);
curl_setopt($c, CURLOPT_NOBODY, true);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($c, CURLOPT_SSL_VERIFYHOST, true);
curl_setopt($c, CURLOPT_URL, $url);
curl_exec($c);
$status = curl_getinfo($c, CURLINFO_HTTP_CODE);
curl_close($c);
return $status;
}
如果您没有 Curl,您可以尝试以下功能:
<?php
function my_get_headers($url ) {
$url_info=parse_url($url);
if (isset($url_info['scheme']) && $url_info['scheme'] == 'https') {
$port = 443;
@$fp=fsockopen('ssl://'.$url_info['host'], $port, $errno, $errstr, 10);
} else {
$port = isset($url_info['port']) ? $url_info['port'] : 80;
@$fp=fsockopen($url_info['host'], $port, $errno, $errstr, 10);
}
if($fp) {
stream_set_timeout($fp, 10);
$head = "HEAD ".@$url_info['path']."?".@$url_info['query'];
$head .= " HTTP/1.0\r\nHost: ".@$url_info['host']."\r\n\r\n";
fputs($fp, $head);
while(!feof($fp)) {
if($header=trim(fgets($fp, 1024))) {
$sc_pos = strpos( $header, ':' );
if( $sc_pos === false ) {
$headers['status'] = $header;
} else {
$label = substr( $header, 0, $sc_pos );
$value = substr( $header, $sc_pos+1 );
$headers[strtolower($label)] = trim($value);
}
}
}
return $headers;
}
else {
return false;
}
}
?>
请注意,对于 HTTPS 支持,您应该启用 SSL 支持。 (在 php.ini 中取消注释 extension=php_openssl.dll)。
如果您无法编辑 php.ini 并且没有 SSL 支持,则很难获取(加密的) header 。
您可以通过以下方式检查您的包装器(openssl 和 httpd):
$w = stream_get_wrappers();
echo 'openssl: ', extension_loaded ('openssl') ? 'yes':'no', "<br>\n";
echo 'http wrapper: ', in_array('http', $w) ? 'yes':'no', "<br>\n";
echo 'https wrapper: ', in_array('https', $w) ? 'yes':'no', "<br>\n";
echo 'wrappers: <pre>', var_dump($w), "<br>";
您可以查看this question解决类似问题。
关于php - 如何检查php中是否存在https站点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17832181/