Vadim Samokhin
Vadim Samokhin

Reputation: 3446

curl connection reuse in php

I use curl in my php application. It looks like that (simplified):

$handle = curl_init();
curl_exec($handle);
curl_close($handle);

As written in Persistence Is The Way to Happiness chapter,

A subsequent request using the same easy handle to the same host might just be able to use the already open connection! This reduces network impact a lot.

So, is it applied to this code? Will the connections be saved and curl_init() use the existing connection? If yes -- how long are they stored?

Upvotes: 1

Views: 4345

Answers (1)

user2629998
user2629998

Reputation:

I haven't tested this myself but here's how I think it should work :

You create a curl instance :

$handle = curl_init();

Then you set up your options, like the URL, the method (post or get) and the query string :

curl_setopt($handle, CURLOPT_URL, "http://stackoverflow.com");

Execute the request :

curl_exec($handle); // execute the request

Change your options, for example change the URL :

curl_setopt($handle, CURLOPT_URL, "http://stackoverflow.com/test/");

Execute the request again, it should be able to reuse the already open connection :

curl_exec($handle);

You can do that as many times as you want with the same curl instance, and it'll reuse connections if possible.

Finally close the connection and delete the curl instance when you're done :

curl_close($handle);

Upvotes: 2

Related Questions