Search code examples
phpcurlfile-get-contents

file_get_contents() or cURL to handle 40* and 50* errors and 200 reponse code


I started my PHP script using file_get_contents(), I'm using an online data base and I can get JSON from it using URL, but sometimes (and I can't help it) I get back some 40* or 50* errors responses code, and I wondered if you guys could tell me what's better to use between cURL and file_get_contents, because basically everytime I'll have to check response code and switch case on it to determine what I do next.

  • 200 => get file
  • 403 => print "error"
  • 502 => print 'bad gateway'
  • ...

Hope I was clear, thanks in advance!


Solution

  • How to get the status of an HTTP response?

    Using cURL

    The function curl_getinfo() get information regarding a specific transfer. The second parameter of this function allows to get a specific information. The constant CURLINFO_HTTP_CODE can be used to get the HTTP status code of the HTTP response.
    curl_getinfo() should be called after curl_exec() and is relevant if curl_exec()' return is not false. If the response is false, don't forget to use curl_error() in this case to get a readable string of the error.

    $url = 'https://stackoverflow.com';
    $curlHandle = curl_init($url);
    curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true); // required to get the HTTP header
    $response = curl_exec($curlHandle);
    $httpCode = $response !== false ? curl_getinfo($curlHandle, CURLINFO_HTTP_CODE) : 0;
    curl_close($curlHandle);
    var_dump($httpCode); // int(200)
    

    Using streams

    The function stream_get_meta_data() retrieves header/meta data from streams/file pointers

    $url = 'https://stackoverflow.com';
    $httpCode = 0;
    if ($fp = fopen($url, 'r')) {
        $data = stream_get_meta_data($fp);
        [$proto, $httpCode, $msg] = explode(' ', $data['wrapper_data'][0] ?? '- 0 -');
    }
    fclose($fp);
    var_dump($httpCode); // int(200)