5

On a page load, I'm consistently requesting data from the same API. Is there any way to keep a cURL connection alive across multiple page loads to reduce handshake time? I know you can make multiple cURL requests with keep-alive headers on the same PHP process easily, but I want a connection to stay alive for say a set amount of time rather than when the process is finished.

It seems like I'd need some sort of Daemon plugin to do this. I'm very open to alternatives solutions. It doesn't have to be cURL. I've been searching and have had no luck whatsoever.

Thanks!

  • To do this, you'd need to have your own middleman that could keep a connection alive with your API provider. It might be an easier option to look at caching API results locally? – scrowler Jan 27 '14 at 20:38
  • They're ugly, but could a frameset be a solution. – MrYellow Sep 05 '14 at 06:13

1 Answers1

0

I would say using pfsockopen() to create a persistent connection would make the trick. You can open the socket to the HTTP API server and then make multiple petitions, and close the socket when the page load ends.

<?php
$host = "protocol://your-api-hostname.com/";
$uri = "/your/api/location";
$port = 80;

// For an HTTP API, for example:
$socket = pfsockopen ($host, $port, $errno, $errstr, 0);
if (!$socket) {
    echo $errno. " - " . $errstr;
} else {
    // You can do here as many requests as you want.
    fputs ($socket, $request1);
    fputs ($socket, $request2);
    // And then keep on reading until the end of the responses
    $i = 0;
    $a = array();
    while (!feof($socket)) {
        $a[$i] = fgets($socket);
        $i++;
    }
fclose($socket);

I don't know if that is exactly what you need but it offers you more options than cURL.

miken32
  • 42,008
  • 16
  • 111
  • 154