Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PHP curl how does one get the response body for a 400 response

Tags:

php

curl

The api I'm calling returns a json object of validation errors with the HTTP code 400. I implemented the client using PHP's curl library, but on error curl_exec returns false. How can I get the response body on error?

Note that I am setting curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

like image 493
Jason Rice Avatar asked Jun 15 '11 20:06

Jason Rice


People also ask

How does PHP handle cURL request?

Next, we've set the CURLOPT_POST option to TRUE to set the request method to HTTP POST. Further, we need to use the CURLOPT_POSTFIELDS option to set the POST data that we want to submit along with the request. Finally, we've used the curl_exec function to execute the cURL request.

What does PHP cURL return?

Functions of cURL in PHP curl_error — It will return the string which represents the error for the particular current session.

Which function in PHP allows you to capture a cURL error?

"You can use the curl_error() function". Proceeds to use curl_errno() in the example. :) @RomanPerekhrest That is terrible advice. Not only is it debatable if a 404 is "an error", curl_exec() will also not return the body anymore if you enable CURLOPT_FAILONERROR .


3 Answers

You can unset CURLOPT_FAILONERROR for once. And adding your error status code to CURLOPT_HTTP200ALIASES as expected might also help.

 curl_setopt($conn, CURLOPT_FAILONERROR, false);
 curl_setopt($conn, CURLOPT_HTTP200ALIASES, (array)400);

(libcurl also has a CURLOPT_ERRORBUFFER, but you cannot use that option from PHP.)

Btw, curl behaves correctly by not returning the response body in case of 4xx errors. Not sure if that can be overriden. So you might have to migrate to PEAR HTTP_Request2 or a similar HTTP request class where you can deviate from the standard.

like image 112
mario Avatar answered Oct 24 '22 18:10

mario


I was able to get content from a 400 response by setting FAILONERROR to false, WITHOUT having to also alias 400 as a normal 200 response.

like image 27
Erutan409 Avatar answered Oct 24 '22 18:10

Erutan409


Add this:

curl_setopt($ch, CURLOPT_HTTP200ALIASES, array(400));
like image 30
Francois Deschenes Avatar answered Oct 24 '22 20:10

Francois Deschenes