title: Is it possible to register some callback function to free resources after a curl request has finished?
body: <p>For some library I want to add a curl debug function which may be called in certain situations. However I stumbled upon some issue with freeing resources.</p>
  
  <p>This is my library function:</p>
  
  <pre><code>/**
   * @param $curlhandle: The curlhandle resource which was created by curl_init();
   * @param null $log_location: Log location folder. If empty the wp-content directory will be used.
   * @param string $log_file_name: The name of the logfile to be written.
   */
  function cis_curl_add_debug($curlhandle, $log_location = null, $log_file_name = "cis-curl-errorlog.txt") {
  
      if(!is_resource($curlhandle)) {
          trigger_error("Incorrect call to cis_curl_add_debug function: Expected curl handle.",E_USER_WARNING);
          return;
      }
  
      if (!$log_location) {
          $log_folder = realpath(WP_CONTENT_DIR . DIRECTORY_SEPARATOR . 'logs');
          if(!is_dir($log_folder)) {
              mkdir($log_folder,776);
          }
      }
  
      $fp = fopen($log_folder . DIRECTORY_SEPARATOR . $log_file_name, 'w');
      curl_setopt($curlhandle, CURLOPT_VERBOSE, 1);
      curl_setopt($curlhandle, CURLOPT_STDERR, $fp);
  
      return $curlhandle;
  }
  </code></pre>
  
  <p>This is a usage example:</p>
  
  <pre><code>    $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json');
  
      $ch = cis_curl_add_debug($ch);
      $result = curl_exec($ch);
      $error = curl_error($ch);
      curl_close($ch);
  </code></pre>
  
  <p>Well this should basically work beside of one little fact: The $fp filepointer is never closed with <code>fclose()</code>. This means that the log file is locked for writing and if I call t his function multiple times the logfile is not available for writing (or if any other application wants to).</p>
  
  <p>So my idea was to register some function - <strong><em>pseudocode</em></strong>:</p>
  
  <pre><code>curl_setopt($curlhandle, CURLOPT_DESTRUCTION_CALLBACK, function () use ($fp) {
      fclose($fp);
  }
  </code></pre>
  
  <p>However I did not find such a possibility yet. Maybe there is a way more obvious solution to this problem?</p>