A few curl requests, when do you need to close the handle?

I am confused with the curl init() and close() functions. I want to know when to close the curl knob in each of these situations:
1. Using a single descriptor to get a "single" URL with various parameters. eg:

 $curl=curl_init('google.com'); curl_setopt($curl,CURLOPT_FOLLOWLOCATION,true); curl_exec($curl); 

Now I want to set FOLLOWLOCATION to false. should i do curl_close ($ curl) and do everything right from the start or just set the parameter and execute it again like this:

 curl_setopt($curl,CURLOPT_FOLLOWLOCATION,false); curl_exec($curl); 

2. Using a single descriptor to get "multiple" URLs. eg:

 $curl = curl_init('google.com'); curl_exec($curl); 

Now I want to get stackoverflow.com. I have to close the descriptor and start from the very beginning, or I can set a different URL without closing the descriptor. eg:

 $curl = curl_init('stackoverflow.com'); curl_exec($curl); 

3. Using a mulit descriptor to retrieve multiple URLs. This is my code:

 $CONNECTIONS=10; $urls=fopen('urls.txt','r'); while(!feof($urls)) { $curl_array=array(); $curl=curl_multi_init(); for($i=0;$i<$CONNECTIONS&&!feof($urls);$i++) //create 10 connections unless we have reached end of file { $url=fgets($urls); //get next url from file $curl_array[$i]=curl_init($url); curl_multi_add_handle($curl,$curl_array[$i]); } $running=NULL; do { curl_multi_exec($curl,$running); }while($running>0); for($i=0;$i<$CONNECTIONS;$i++) { $response=curl_multi_getcontent($curl_array[$i]); curl_multi_remove_handle($curl,$curl_array[$i]); curl_close(($curl_array[$i])); } curl_multi_close($curl); } 

As you can see: after receiving the contents of each individual descriptor, I delete this descriptor from the multiple descriptor, closing one descriptor, and then closing the multiroom after the for loop. Is this practice right or am I APPLYING to pens?
thanks

+4
source share
1 answer

when to close the handle?

Simply put, you close it when you're done.

To answer your specific questions:

  • If you plan to reuse the curl knob (separate resource), close it when you're done.
  • If you have several curl knobs (multiple resources), you can run them together with the curl_multi_* functions, as you showed, or run them sequentially and close the curl knob when you are done with this resource (see # 1).
  • It looks right to me.

Note that if you reuse the curl knob, remember things like caching, redirection, and other parameters that can affect multiple requests of the same resource.

I would advise you to develop your code to request each resource once.

+3
source

All Articles