I have an online function which needs to connect to the quickest server out of a few websites in an array in PHP.
Here is how far I got. I used Fopen to check if the website is online and foreach to redirect to it. I figured that the quickest server would redirect first, but instead it just redirected the last item in the array in the URL.
Here's how far I got:
// 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...';
Thanks in advance. I look forward to seeing your replies :)
It looks that Php does not provide a callback-like option to receive a succesful or failed connection on socket asynchronously.
Anyway there are great libs for Php out there. I'm also interested on this feature for Php.
You could install with composer the following lib https://github.com/reactphp/socket
seems pretty straight forward to use.
Find it slightly adapted to your case:
$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();
Good luck!