Reading body errors in PHP curl_exec

Possible duplicate:
Using curl php how to get response body for 400 response

When using PHP curl_exec to call the RESTful API, the documentation says http://php.net/manual/en/function.curl-exec.php

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

If curl_exec fails, it returns false. However, the remote server may have attempted to return a useful message for this error. How can we access this message using curl_exec when it just returns false?

For example, the remote API may return this message and an HTTP 400 status code:

{"Items":[{"Field":"FirstName","Description":"FirstName is required and cannot be null."}]} 

Currently, I cannot read this error message that was returned; instead, everything I get is false. I also looked at curl_info. I have a returntransfer.

In C #, I would use the exception.Response.GetResponseStream method and write:

  private static string Post(WebClient client, string uri, string postData) { string response = string.Empty; try { response = client.UploadString(uri, "POST", postData); } catch (WebException ex) { var stream = ex.Response.GetResponseStream(); // here if (stream != null) { using (var reader = new StreamReader(stream)) { response = reader.ReadToEnd(); } } } return response; } 

How can this be done in PHP? Is curl_exec the correct method or should I use something else?

+4
source share
1 answer
+1
source

Source: https://habr.com/ru/post/1437580/


All Articles