What are the best practices for optimizing PHP scripts that check multiple links for availability?

When optimizing PHP scripts that check multiple links for availability, it is important to use asynchronous requests to avoid blocking the script while waiting for each link to respond. This can be achieved by utilizing libraries like Guzzle or cURL to send multiple requests concurrently. Additionally, caching responses can help reduce the number of requests made to the same link.

<?php

// Example using Guzzle library to send asynchronous requests to check multiple links for availability

require 'vendor/autoload.php'; // Include Guzzle library

$links = ['https://example.com', 'https://google.com', 'https://github.com']; // Array of links to check

$promises = [];
$client = new GuzzleHttp\Client();

foreach ($links as $link) {
    $promises[$link] = $client->getAsync($link);
}

$results = GuzzleHttp\Promise\settle($promises)->wait();

foreach ($results as $link => $result) {
    if ($result['state'] === 'fulfilled') {
        echo $link . ' is available' . PHP_EOL;
    } else {
        echo $link . ' is not available' . PHP_EOL;
    }
}

?>