Getting HTTP code in PHP using curl

后端 未结 9 2147
无人共我
无人共我 2020-11-28 03:43

I\'m using CURL to get the status of a site, if it\'s up/down or redirecting to another site. I want to get it as streamlined as possible, but it\'s not working well.

<
9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 04:14

    First make sure if the URL is actually valid (a string, not empty, good syntax), this is quick to check server side. For example, doing this first could save a lot of time:

    if(!$url || !is_string($url) || ! preg_match('/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(\/.*)?$/i', $url)){
        return false;
    }
    

    Make sure you only fetch the headers, not the body content:

    @curl_setopt($ch, CURLOPT_HEADER  , true);  // we want headers
    @curl_setopt($ch, CURLOPT_NOBODY  , true);  // we don't need body
    

    For more details on getting the URL status http code I refer to another post I made (it also helps with following redirects):

    • How can I check if a URL exists via PHP?

    As a whole:

    $url = 'http://www.example.com';
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, true);    // we want headers
    curl_setopt($ch, CURLOPT_NOBODY, true);    // we don't need body
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_TIMEOUT,10);
    $output = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    echo 'HTTP code: ' . $httpcode;
    

提交回复
热议问题