开发者

verify URL is live and running or not

I will be taking URL from user. Now I need to verify whether address is live or not.

For example:

If user enters "google.com", then I will pass "google.com" 开发者_高级运维as argument to some function, and function will return me TRUE if URL is live, upload and running, otherwise FALSE.

Any in-built function or some help.


I'd suggest using get_headers($url) and checking to see if one of your responses contains "200 OK". If so, then the site is alive and responded with a valid request. You can also check for other status codes if you want, such as redirects and whatnot.


function url_exists($url){
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch, CURLOPT_TIMEOUT,5);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,5);
    curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);  
    return $code == 200;
}

You may want to support additional httpcodes such as 201, but that's up to you.

EDIT:

AS a note this gives you better control over the timeouts you want to use before failing.


Try fopen

$f = @fopen('http://www.google.com/', 'r');
if (is_resource($f)) {
  fclose($f);
  return true;
} else { return false; }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜