Try   HackMD

PHP, cURL and Memory Management

About cURL (for Client URL):

PHP supports libcurl, a library created by Daniel Stenberg, that allows you to connect and communicate to many different types of servers with many different types of protocols.

Source: https://www.php.net/manual/en/intro.curl.php.

Any cURL session must be:

  1. Initialized by a call to curl_init().
  2. Closed by a call to curl_close() in order to free up system resources.

What is the impact of not explicitly calling curl_close()?
Will it generate memory leaks?

TL;DR: PHP memory management will properly clean unclosed sessions at process exit.

The following is the result of some investigations in PHP internals.

PHP version used at time of writing is 7.4.2.

Destructor Registration

When cURL package functions are registered (using PHP_MINIT_FUNCTION extension function), a destructor _php_curl_close() associated to resource type "curl" is registered, using function zend_register_list_destructors_ex():

le_curl = zend_register_list_destructors_ex(_php_curl_close, NULL, "curl", module_number);

More information at page Playing with resources.

Curl Session Workflow

Basic workflow of a cURL session:

  1. Initialize cURL session by calling curl_init().
    Many sub-functions calls will be made:

    1. Call to curl_easy_init().

    2. Call to alloc_curl_handle().

      ​​​​​​​​ch = alloc_curl_handle();
      
    3. Call to zend_register_resource().
      This will allow destruction of handle ch at the end of the process.

      ​​​​​​​​ZVAL_RES(return_value, zend_register_resource(ch, le_curl));
      
  2. Subsequent calls to cURL functions using handle returned at step 1.

  3. Close cURL session by calling curl_close().

Memory Management

If curl_close() function is not called, the session handle will stay in the list of resource types (as registered at step 1.3).
At the end of the process, items of this list will be fetched by PHP interpreter and deleted using their related destructors.

Resources