Permanent cURL connection for multiple page loads in PHP

When loading a page, I constantly request data from the same API. Is there a way to keep a live cURL connection across multiple page loads in order to shorten the setup time? I know that you can make several cURL requests with keep-alive headers on the same PHP process, but I want the connection to stay alive, for example, for a certain amount of time, and not to end the process.

I seem to need some kind of Daemon plugin for this. I am very open to alternative solutions. It should not be cURL. I searched and had no luck.

Thanks!

+4
source share
1 answer

I would say using pfsockopen()to create a permanent connection would do the trick. You can open the socket on the HTTP API server, and then make several petitions and close the socket when the page finishes loading.

<?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 do not know if this is exactly what you need, but it offers more options than cURL.

0
source

Source: https://habr.com/ru/post/1523959/


All Articles