Search code examples
phpcurlhttp-headers

How to analyze headers in PHP


I'm using a file_get_contents to interact with an API for simple GET requests... however sometimes it throws headers signifying there's been an error. How can I get these headers and determine if there's a problem?


Solution

  • Use curl instead of file_get_contents.

    See: http://www.php.net/manual/en/curl.examples-basic.php

    I imagine if your communicating with a REST Api then your actaully wanting the Http Status code returned. In which case you could do something like this:

    <?php
    $ch = curl_init("http://www.example.com/api/users/1");
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_exec($ch);
    if(curl_getinfo($ch, CURLINFO_HTTP_CODE) == 501) {
        echo 'Ops it not implemented';
    }
    fclose($fp);
    ?>