Andres SK
Andres SK

Reputation: 10982

cURL function to retrieve JSON data in PHP

I coded this function to retrieve JSON data from an API (which returns data in JSON format).

function file_get_contents_curl($url,$json=false){
    $ch = curl_init();
    $headers = array();
    if($json) {
        $headers[] = 'Content-type: application/json';
        $headers[] = 'X-HTTP-Method-Override: GET';
    }
    $options = array(
        CURLOPT_URL => $url,
        CURLOPT_HTTPHEADER => array($headers),
        CURLOPT_TIMEOUT => 5,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_HEADER => 0,
        CURLOPT_FOLLOWLOCATION => 1,
        CURLOPT_MAXREDIRS => 3,
        CURLOPT_USERAGENT => 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)'
    );
    curl_setopt_array($ch,$options);
    $response = curl_exec($ch);
    curl_close($ch);
    if($response === false) {
        return false;
    } else {
        return $response;
    }
}

If $response is in fact ===false, does it mean that cURL could not connect to the URL? Or could it also be that the API itself returned nothing (but the connection was successful)?

How do I know if cURL connects properly to the URL?

Upvotes: 1

Views: 1263

Answers (2)

Trott
Trott

Reputation: 70183

If $response === false then curl failed.

It does not mean that curl succeeded but got no content. Since you've turned on CURLOPT_RETURNTRANSFER, that means the response will be returned as a string. So, no content should be indicated by $response === ''.

Where you would run into trouble is if you only had two equal signs rather than three. With three, you're doing type checking, so the boolean false is not the same as an empty string.

Upvotes: 1

Paulo H.
Paulo H.

Reputation: 1258

PHP curl doc says:

Return Values

Returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.

Check error using curl_error

Upvotes: 1

Related Questions