Current Location: Home> Latest Articles> Avoid errors in calling curl_close when a cURL session is not initialized

Avoid errors in calling curl_close when a cURL session is not initialized

gitbox 2025-05-29

cURL is a very common library when using PHP for network requests. However, if the curl_close function is called without successfully initializing the cURL session, a warning will be triggered and may even cause an exceptional interruption of the program. Therefore, understanding how to safely manage the life cycle of a cURL session is important for building robust code.

1. Error scenario example

Here is a typical error example:

 <?php

$ch = curl_init();

// Some conditions cause return or an exception to occur
if (!$ch) {
    echo "cURL Initialization failed";
}

// Regardless of whether the initialization is successful or not,All called curl_close
curl_close($ch); // if $ch for false,Will trigger a warning

In the above code, if curl_init() returns false (although it is almost impossible under normal circumstances), or $ch is accidentally modified to a non-resource type, and then curl_close($ch) will occur.

2. Correct defensive programming method

To avoid this error, you should confirm whether $ch is a valid cURL handle before calling curl_close . You can use is_resource() or curl_reset() return type judgment to PHP 8.0 or above.

Method 1: Check whether it is a valid resource (PHP 7 and below)

 <?php

$ch = curl_init();

if ($ch === false) {
    echo "cURL Initialization failed";
} else {
    // Perform related operations
    curl_setopt($ch, CURLOPT_URL, "https://gitbox.net/api/data");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);

    // Safely shut down
    curl_close($ch);
}

Method 2: Use instanceof CurlHandle (PHP 8 and above)

 <?php

$ch = curl_init();

if ($ch instanceof CurlHandle) {
    curl_setopt($ch, CURLOPT_URL, "https://gitbox.net/api/data");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);

    curl_close($ch);
} else {
    echo "cURL Initialization failed";
}

CurlHandle is an object type introduced in PHP 8 to replace the original cURL resource. Checking via instanceof is more semantic and safe.

3. Use try-catch to wrap the package process (recommended)

If your business logic is relatively complicated, it is recommended to use an exception handling structure to wrap the entire process:

 <?php

$ch = null;

try {
    $ch = curl_init();

    if ($ch === false) {
        throw new Exception("Unable to initialize cURL Session");
    }

    curl_setopt($ch, CURLOPT_URL, "https://gitbox.net/api/data");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);

    if ($response === false) {
        throw new Exception("cURL Request failed:" . curl_error($ch));
    }

    echo $response;
} catch (Exception $e) {
    echo "mistake:" . $e->getMessage();
} finally {
    if (is_resource($ch) || (PHP_VERSION_ID >= 80000 && $ch instanceof CurlHandle)) {
        curl_close($ch);
    }
}

in conclusion

Whether you are using PHP 7 or PHP 8, ensuring that the validity of the handle is verified before calling curl_close is a basic but critical defensive programming practice. This not only prevents runtime errors, but also improves the stability and robustness of the program.

Always remember: Don't assume that initialization will be successful, safety is always more effective than repair.