Possible Duplicate:
Using PHP curl how does one get the response body for a 400 response
When using PHP's curl_exec to call a RESTful API the documentation says http://php.net/manual/en/function.curl-exec.php
Returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.
When curl_exec fails it returns false. However the remote server might have tried to return a helpful message to go with that error. How can we access this message using curl_exec, when it just returns false?
For example the remote API might be returning this message and a HTTP 400 status code:
{"Items":[{"Field":"FirstName","Description":"FirstName is required and cannot be null."}]}
Currently I am unable to read this error message that has been returned, instead all I get is false. I have looked at curl_info too. I do have returntransfer set on.
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 right method or should I use something else?
curl_setopt($curl, CURLOPT_FAILONERROR, false);
andcurl_setopt($curl, CURLOPT_HTTP200ALIASES, array(400));
set, $curl_result is only returning "Bad Request" (a small improvement - before it was returning false) – Rybinsk$curl_result
? The return value ofcurl_exec()
? – Phosphorous