php cURL判断网站是否有效

办法1

<?php
function data($url) {
if(substr($url,0,7)!="http://" && substr($url,0,8)!="https://"){
$url = "http://".$url;
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
$contents = curl_exec($ch);
curl_close($ch);
if($contents === false){
$tmp = 'false';
}else{
$tmp = '200';
}
return $tmp;
}
?>

使用方法:

$url='http://www.98lm.com';
echo data($url);

显示 false 为无效连接 \显示 200  为有效连接

<?php
function httpcode($url){
$ch = curl_init();
$timeout = 3;
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch,CURLOPT_URL,$url);
curl_exec($ch);
return $httpcode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
curl_close($ch);
}
?>

使用方法:

<?php 
echo httpcode('http:/www.98lm.com/');
?>

如果显示为200则正常,如果显示其它值表示不正常;$timeout后面的3是设置超时秒数。

赞 (0)