Reputation: 2187
I am using cURL to retrieve a file from a server, I wonder is there a way to specify a return value when curl_exec() fails. My code is like this:
if (!$result = curl_exec($curl)){
echo "something is wrong.";
exit;
}
/**
*the rest of the script
*/
When the exec() call fails, the echo statement is not printed on the page, and apparently the exit() is not called as well, causing my following scripts to execute as normal. I noticed that when curl_exec() fails, it does not give you FALSE, it just gives you a something like "NOT FOUND" page, I guess this is where my problem is. Is there any way that can force it to return a boolean or a string so that I can do the condition test? Many thanks.
Upvotes: 1
Views: 3198
Reputation:
Try:
$result = curl_exec($curl);
if (!$result){
echo "something is wrong.";
exit;
}
The condition above will be met, only if curl_exec()
returns false. curl_exec()
returns false when it fails to access the target link you provided. Even if the like returns a 404 error, curl_exec()
will not return false, as it had no problems accessing the link.
Upvotes: 0
Reputation: 437346
curl_exec
will only return false
if the HTTP request did not complete successfully from a technical standpoint. If the request itself does complete but the result is not what you expected (e.g. the server responded with a 404) it will correctly return true
or the result (depending on CURLOPT_RETURNTRANSFER
being set or not).
Therefore you have to check for this eventuality separately. For example:
if (!$result = curl_exec($curl)){
echo "request totally failed.";
exit;
}
$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($code >= 400) {
echo "the server responded with an error code.";
exit;
}
See the list of HTTP status codes for more information.
Upvotes: 1