How can I check if a URL exists via PHP?

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

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

22条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 05:08

    pretty fast:

    function http_response($url){
        $resURL = curl_init(); 
        curl_setopt($resURL, CURLOPT_URL, $url); 
        curl_setopt($resURL, CURLOPT_BINARYTRANSFER, 1); 
        curl_setopt($resURL, CURLOPT_HEADERFUNCTION, 'curlHeaderCallback'); 
        curl_setopt($resURL, CURLOPT_FAILONERROR, 1); 
        curl_exec ($resURL); 
        $intReturnCode = curl_getinfo($resURL, CURLINFO_HTTP_CODE); 
        curl_close ($resURL); 
        if ($intReturnCode != 200 && $intReturnCode != 302 && $intReturnCode != 304) { return 0; } else return 1;
    }
    
    echo 'google:';
    echo http_response('http://www.google.com');
    echo '/ ogogle:';
    echo http_response('http://www.ogogle.com');
    

提交回复
热议问题