Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to close a cURL connection?

Tags:

php

curl

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.

like image 537
kouton Avatar asked Mar 22 '14 04:03

kouton


1 Answers

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.

like image 62
h2ooooooo Avatar answered Sep 18 '22 19:09

h2ooooooo