$site = 'https://twitter.com/';
$username = 'SteveMartinToGo';
$url = $site.$username;
function urlExists($url=NULL) {
if($url == NULL) return false;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($httpcode >= 200 && $httpcode < 400){
return true;
} else {
return false;
}
}
if(urlExists($url)) {
echo 'url exists';
} else {
echo 'url does not exist';
}
这样做的问题是某些网站(如 Facebook)将返回 200 而不是 404,因此 URL 将显示为存在,即使它不存在。另外,我从其他地方得到了这个功能(虽然不记得在哪里),所以我不想因为那个代码而受到赞扬。希望能帮助到你...
编辑:由于 fred-ii 的鹰眼和建议而更新。:)