user1032531 user1032531 - 9 months ago 48
PHP Question

When should curl_close() be used?

The below script will operate indefinitely and will be initiated by using

php myscript.php
. will only respond if it has something to communicate to
php myscript.php
, and the below curl request will timeout before longpolling.php will reach its time limitation.

Should I close and reopen the curl connection each loop, or keep it open indefinitely.

// php myscript.php
$ch = curl_init();
curl_setopt_array( $ch, $options );
while (true) {
$rsp = curl_exec( $ch );
// Do something
//curl_close( $ch ); //should I close and reopen?

Answer Source

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

Here is also a nice benchmark for this issue.