Search code examples
curlhttp-status-codes

Issue getting HTTP response Status code from Headers while using curl


Am using curl to fetch some data from a payment gateway,, the gateway returns 500 status code at times and 200 status code in the headers at other times. I am trying to get the status code from the headers using curl but it is showing zero (which is the exit code) instead of 200 or 500 (status code).

Am using curl_getinfo($ch, CURLINFO_HTTP_CODE); which aint working...

Curl function

public function global_Curl_payStat($data, $url, $try = 1)
    {
        //dd($_ENV['API_ENDPOINT_NGINX_IP'] . '/' . $url);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, ($_ENV['API_ENDPOINT_NGINX_IP'] . '/' . $url));
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //Prevents usage of a cached version of the URL
        curl_setopt($ch, CURLOPT_FRESH_CONNECT, TRUE);
        //Listen for status code to see if 200 or 500
        $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $response = json_decode(curl_exec($ch));
        dd($statusCode);

        curl_close($ch);

        return $response;
    }

Solution

  • Your call to curl_getinfo() is coming before you have actually called it with curl_exec(). There is no info until you execute :)

    $response = json_decode(curl_exec($ch));
    //Listen for status code to see if 200 or 500
    $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);