How to catch curl errors in PHP

Harish Kurup picture Harish Kurup · Oct 21, 2010 · Viewed 271.8k times · Source

I am using PHP curl functions to post data to the web server from my local machine. My code is as follows:

$c = curl_init();
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($c);
if (curl_exec($c) === false) {
    echo "ok";
} else {
    echo "error";
}
curl_close($c);

Unfortunately I am not able to catch any errors like 404, 500 or network failure. So how will I get to know that data was not posted to or retrieved from the remote?

Answer

Sarfraz picture Sarfraz · Oct 21, 2010

You can use the curl_error() function to detect if there was some error. For example:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $your_url);
curl_setopt($ch, CURLOPT_FAILONERROR, true); // Required for HTTP error codes to be reported via our call to curl_error($ch)
//...
curl_exec($ch);
if (curl_errno($ch)) {
    $error_msg = curl_error($ch);
}
curl_close($ch);

if (isset($error_msg)) {
    // TODO - Handle cURL error accordingly
}

See the description of libcurl error codes here

See the description of PHP curl_errno() function here

See the description of PHP curl_error() function here