12

When is it necessary to close curl connection and release resources consumed by it?

Why do I ask this question, well quite simply because I was told, that PHP garbage collector does all of this and sometimes there is no need to close DB connection or call the __destruct method to release resources.

Since, that moment I actually started to think about where do I need to call it then? At the moment I'm interested with that question since I writing a small library for curl and I'd like to understand when do I need to user curl_close() function.

Thank you all for discussion and explanation of it.

T.Todua
  • 53,146
  • 19
  • 236
  • 237
Eugene
  • 4,352
  • 8
  • 55
  • 79
  • Be carefull on using this for changing data by curl (post, put etc), for it can reuse old data in the background, see my answer: https://stackoverflow.com/a/67266458/4699609 – flexJoly Apr 26 '21 at 12:26

3 Answers3

12

Results for 100 times curl_exec (fetching url with cache avoiding):

Executing in every loop:

for ($i = 0; $i < 100; ++$i) {
    $c = curl_init();
    curl_setopt($c, CURLOPT_URL, "http://www.google.com/?rand=" . rand());
    curl_exec($c);
    curl_close($c);
}

8.5 seconds

Executing only once :

$c = curl_init();
for ($i = 0; $i < 100; ++$i) {
    curl_setopt($c, CURLOPT_URL, "http://www.google.com/?rand=" . rand());
    curl_exec($c);
}
curl_close($c);

5.3 seconds


Decision: get used to always use optimal code in your tasks. (source)

Community
  • 1
  • 1
T.Todua
  • 53,146
  • 19
  • 236
  • 237
5

as far as i understand it. The GC only cleans up resources that are no longer used/referenced. as whenever the curl variable fall out of scope, it'll be cleaned up. But that might only happen after the script has finished, or whenever the session is destroyed (depending on scope).

But to be on the safe side, just follow common sense.. close it when its no longer needed.

Oliver O'Neill
  • 1,229
  • 6
  • 11
1

Depends. In my case since I was initializing curl instance in my custom CurlClient constructor

$this->ch = curl_init();

And then using same $curlClient object for multiple api calls, closing the instance

curl_close($this->ch);

would affect other API calls. Methods using the same object will not work, so I'm not closing it.

RediOne1
  • 10,389
  • 6
  • 25
  • 46
R Sun
  • 1,353
  • 14
  • 17