When should curl_close () be used?

The below script will run endlessly and will be triggered using php myscript.php .

http://example.com/longpolling.php will only respond if it has something to communicate with php myscript.php and the request below curl expires before longpolling.php reaches its time limit .

Should I close and reopen the curl of each cycle or keep it open indefinitely.

 <?php // php myscript.php $options=[ CURLOPT_URL=>'http://example.com/longpolling.php', CURLOPT_RETURNTRANSFER=>true, CURLOPT_CONNECTTIMEOUT => 300, CURLOPT_TIMEOUT=> 300 ]; $ch = curl_init(); curl_setopt_array( $ch, $options ); while (true) { $rsp = curl_exec( $ch ); // Do something //curl_close( $ch ); //should I close and reopen? } 
+6
source share
2 answers

If the URLs are on the same server, reusing the handle will increase performance. cURL will reuse the same TCP connection for each HTTP request to the server.

It is also a good benchmark for this problem.

+2
source

You are missing the exit condition. Assuming this is a response from a remote script, your code should be:

 <?php // php myscript.php $options=[ CURLOPT_URL=>'http://example.com/longpolling.php', CURLOPT_RETURNTRANSFER=>true, CURLOPT_CONNECTTIMEOUT => 300, CURLOPT_TIMEOUT=> 300 ]; $ch = curl_init(); curl_setopt_array( $ch, $options ); $rsp = false; while (!$rsp) { $rsp = curl_exec( $ch ); } curl_close( $ch ); // Do something 
0
source

Source: https://habr.com/ru/post/1011884/


All Articles