Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should curl_close() be used?

The below script will operate indefinitely and will be initiated by using php myscript.php.

http://example.com/longpolling.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
// 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?
}
like image 466
user1032531 Avatar asked Oct 31 '16 12:10

user1032531


People also ask

Why we use curl_ setopt?

Its purpose is simply to execute the predefined CURL session (given by ch). curl_setopt($ch, option, value) set an option for a cURL session identified by the ch parameter. Option specifies which option is to set, and value specifies the value for the given option.

How do you end a cURL session?

The Curl client can tell the server that it wants to close the connection by sending the "Connection: close" header to the server. To pass the "Connection: close" header to Curl, you can use the -H command-line option. In this Curl Close Connection example, we are sending a request to the ReqBin echo URL.

What does CURLOPT_ RETURNTRANSFER do?

CURLOPT_RETURNTRANSFER: Converts output to a string rather than directly to the screen.


1 Answers

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.

like image 171
secelite Avatar answered Sep 24 '22 12:09

secelite