Problem with cURL, get message body even with http! = 200

5

I have a request in my API:

$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, 'link da api');
curl_setopt( $ch, CURLOPT_FAILONERROR, true );
curl_setopt( $ch, CURLOPT_TIMEOUT, 10 );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $params);
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'POST' );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, true );
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 2 );

$db_save_user = json_decode(curl_exec($ch)); //recupera o json quando o httpstatus = 200
$http_status = curl_getinfo( $ch, CURLINFO_HTTP_CODE );

Using postman , I get the expected error, and the json response I would like to use this information in case the user accesses the page or refreshes the page, instead of creating a new user, he continues with the registration setting the information that is already saved in the bank, but I can not find the method to retrieve this information when there is httpstatus != 200 at all!

Forexample,injs/jquery,inaajaxrequest,whenthereisaserverfailure,thereisstillthepossibilityofretrievingjsonresponse:

jQuery.ajax({url:"link da api", 
    type: "POST",
    data: data,
    success: function(returnjson){
        console.log(returnjson.id_customer);
        return true;
    },
    error: function(returnjson) {
        if(returnjson.status == 409){
            console.log(returnjson.responseJSON.id_customer);
            return true;
        }else{
            alert("Ocorreu algum erro, tente novamente ou entre em contato com o suporte técnico.");
        }
        return false;
    }
});
    
asked by anonymous 06.10.2016 / 17:04

1 answer

5

The problem is exactly on the third line.

curl_setopt( $ch, CURLOPT_FAILONERROR, true );

According to the CURL documentation :

  

A long parameter set to 1 tells the library to fail the request if the    HTTP CODE returned equal to or greater than 400. The default action   would be to return the page normally, ignoring that code.

Translating (edited for better understanding):

  

The parameter set to "1" tells the library to "kill"   the request if the HTTP CODE returned is equal to or greater than 400. The action   default would be to return the page normally, ignoring this code.

So what's happening is this:

Using true in CURLOPT_FAILONERROR you are closing CURL when HTTP_CODE is not 200, as pointed out. As a result you can not get the result of the page, nor can json_decode() .

Solution:

Remove the line ( curl_setopt( $ch, CURLOPT_FAILONERROR, true ); ) or make it as false . This will cause CURL to return the page even if HTTP CODE is greater than or equal to 400!

    
07.10.2016 / 05:52