Search code examples
phphttpcurlconnection-poolingpersistent-connection

php and persistent HTTP connections


There is any way you can use HTTP persistent connections between requests ? I don't see the CURL extensions having a way to create a pool of connections that's used by all requests as there are in other extensions for mysql, redis, pg.

From what I see you can use persistent http connections only inside the same request.

Silviu


Solution

  • The pecl_http extension for PHP uses libcurl and allows you to open a persistent TCP connection that can be reused:

    $client = new http\Client('curl', $persistentHandleID); 
    $request = new http\Client\Request('GET', 'http://example.com/');
    $client->enqueue($request);
    $client->send();
    $response = $client->getResponse($request);
    

    If another $client running on the same PHP process (possibly during a different PHP request) accesses the same host and shares the same $persistentHandleID, it will send its HTTP requests over the same TCP connection as before.

    The TCP connection will be kept alive until the PHP module is shut down or until the $client sends Connection: Close or forbids further use of the connection:

    $client->setOptions(['forbid_reuse' => true, … ]);