How can one optimize the script for checking server availability to reduce the time taken for the determination?

To optimize the script for checking server availability and reduce the time taken for the determination, one can implement asynchronous requests using PHP cURL multi functions. This allows multiple requests to be sent concurrently, improving the efficiency of checking server availability.

<?php
$urls = array(
    'http://example.com',
    'http://example2.com',
    'http://example3.com'
);

$mh = curl_multi_init();
$handles = array();

foreach ($urls as $url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    curl_multi_add_handle($mh, $ch);
    $handles[] = $ch;
}

$active = null;
do {
    curl_multi_exec($mh, $active);
} while ($active > 0);

foreach ($handles as $handle) {
    $url = curl_getinfo($handle, CURLINFO_EFFECTIVE_URL);
    $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
    
    echo "URL: $url - Status Code: $httpCode\n";
    
    curl_multi_remove_handle($mh, $handle);
    curl_close($handle);
}

curl_multi_close($mh);
?>