0

我有一个在线功能,需要连接到 PHP 数组中几个网站中最快的服务器。

这是我走了多远。我使用 Fopen 检查网站是否在线并使用 foreach 重定向到它。我认为最快的服务器会首先重定向,但它只是重定向了 URL 中数组中的最后一项。

这是我走了多远:

// The URLs to check in an Array.
$urls = ['website1.com', 'website2.com', 'website3.com'];
// Get the fastest server (the fastest server should redirect first)
foreach($urls as $proxy) {
    if ($socket = @ fsockopen($proxy, 80, $errno, $errstr, 30)) {
        header('Location: https://'.$proxy.'');
        fclose($socket);
    } else {}
}
echo 'Connecting to the fastest server...';

提前致谢。我期待看到你的回复:)

4

1 回答 1

1

看起来 Php 没有提供类似回调的选项来异步接收套接字上的成功或失败连接。

无论如何,那里有很棒的 PHP 库。我也对 PHP 的这个功能感兴趣。
您可以使用composer安装以下库https://github.com/reactphp/socket
似乎很容易使用。

发现它略微适合您的情况:

$loop = React\EventLoop\Factory::create();
$connector = new React\Socket\Connector($loop);
$urls = ['website1.com', 'website2.com', 'website3.com'];
foreach($urls as $proxy) {

  $socket = new React\Socket\Server($proxy, $loop);

  $socket->on('connection', function (ConnectionInterface $conn) {
    header('Location: https://'.$proxy.'');
    $conn->close();
  });
});

$loop->run();

祝你好运!

于 2018-10-21T09:22:41.200 回答