7

I created a wrapper function for cURL in PHP. Its simplified version looks like this:

function curl_get_contents($url, $try = 1) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, '1');
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, '1'); 

    // Execute the curl session
    $output = curl_exec($ch);

    if ($output === FALSE) {
        if ($try == 1) { //Try again
            return $this->curl_get_contents($url, 2);
        } else {
            return false;
        }    
    }        
}

As you can see, I force a retry of the function if it fails. Do I need to run curl_close()? Does PHP close all handles at the end of the script?

UPDATE

The linked question is extremely vague in its answer and doesn't support itself with data. I would really appreciate an answer based on perhaps a profiler that shows that PHP closes the connection immediately.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
kouton
  • 1,941
  • 2
  • 19
  • 34
  • possible duplicate of [When to use cURLs function curl\_close?](http://stackoverflow.com/questions/3849857/when-to-use-curls-function-curl-close) – bansi Mar 22 '14 at 04:13
  • @bansi, I came upon that answer before. However, it's rather vague, and doesn't point to documentation or any source. – kouton Mar 22 '14 at 04:32

2 Answers2

8

No you don't - the garbage handler will take care of it for you, and you don't need to bother cleaning up memory yourself.

The precise answer is described in the manual entry "Resources":

Freeing resources

Thanks to the reference-counting system introduced with PHP 4's Zend Engine, a resource with no more references to it is detected automatically, and it is freed by the garbage collector. For this reason, it is rarely necessary to free the memory manually.

Note: Persistent database links are an exception to this rule. They are not destroyed by the garbage collector. See the persistent connections section for more information.

h2ooooooo
  • 39,111
  • 8
  • 68
  • 102
4

No, it is really an optional step. However, it may be useful if you wish to re-use the same variable and initialize it with a different set of options.

gat
  • 2,872
  • 2
  • 18
  • 21