开发者

Getting multiple http response codes using cURL?

开发者 https://www.devze.com 2023-02-28 17:36 出处:网络
Please take a look at this sample code: function http_response($url开发者_高级运维) { $ch = curl_init();

Please take a look at this sample code:

function http_response($url开发者_高级运维)
{
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, TRUE);
        curl_setopt($ch, CURLOPT_NOBODY, TRUE); // remove body
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $head = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        echo $httpCode ;
}

this code will print the httpCode of the given url. I have couple of questions:

  1. Can I get rid of some setopt() lines here and still getting httpCode?
  2. What about if I want to check multiple urls at the same time? Can I modify the code to do that?
  3. Can I do the same functionality in a simpler way using libraries different than cURL?

Thanks :)


  • You should be able to remove CURLOPT_HEADER and CURLOPT_NOBODY and still get the same result.
  • You could do that like this:

    $urls = array(
        'http://google.com',
        'http://facebook.com'
    );
    
    $status = array();
    
    foreach($urls as $url){
        $status[$url] = http_response($url);
    }
    

    Try print_r($status); after this and you'll see the result.

  • You could do this with file_get_contents and $http_response_header, to learn more: http://www.php.net/manual/en/reserved.variables.httpresponseheader.php I would however recommend using cURL anyway.


*2. to check multiple urls you have to use this function in a loop, in any programming language 1 response from a server = 1 connection to that server. If you want to use 1 function to get responses from multiple servers you can always pass an array to the function and do the loop inside the function

*3. you can try this way:

function get_contents() {
  file_get_contents("http://example.com");
  var_dump($http_response_header);
}


get_contents();
0

精彩评论

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