Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Patwan's avatar

Problem getting HTTP status code while using PHP Curl

Am using curl to post some data to a payment gateway, at times the server returns a status code of 200 while other times I get 500 status code. I want to fetch only the status code from the headers from the response I get which aint working as expected.

The code below is the curl fun

 //Curl function 
    public function curl($data, $url)
    {
        //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 HTTP errors status code
        $code=$(curl -s -o file -w '%{response_code}' , $_ENV['API_ENDPOINT_NGINX_IP'] . '/' . $url);
        dd($code);
}

0 likes
1 reply
lostdreamer_nl's avatar

You should simply do it like this:


        $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);
        $response = curl_exec($ch);
        $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        dd($statusCode, $response);

There is no point in mixing PHP curl setopt and then running a curl command via console.

note that curl_getinfo($ch, CURLINFO_HTTP_CODE) has to come after curl_exec($ch) or it returns 0

Please or to participate in this conversation.