How to catch cURL Errors in PHP

  1517 views   9 months ago PHP

While working with API request using PHP cURL request, you might get null response in curl request. This is because your cURL request failed due to error.

In PHP curl there is curl_error() function which catch the error. Here is example code for cURL error.


$url = '';

$data = [
    'name' => 'Harsukh Makwana',
    'email' => '[email protected]'

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// required for HTTP error codes to be reported
curl_setopt($ch, CURLOPT_FAILONERROR, true);

$result = curl_exec($ch);

if (curl_errno($ch)) {
    $error_msg = curl_error($ch);

if (isset($error_msg)) {
    // echo($error_msg);

I hope it will help you.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]