How can I check if a URL exists via PHP?

前端 未结 22 1872
天涯浪人
天涯浪人 2020-11-22 04:13

How do I check if a URL exists (not 404) in PHP?

22条回答
  •  天命终不由人
    2020-11-22 05:05

    cURL can return HTTP code I don’t think all that extra code is necessary?

    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<300){
                return true;
            } else {
                return false;
            }
        }
    

提交回复
热议问题