What are the potential pitfalls of using fopen() with a timeout for server availability checks in PHP?

Using fopen() with a timeout for server availability checks in PHP can lead to potential pitfalls such as long response times if the server is unreachable, which can impact the overall performance of your application. To solve this issue, you can set a timeout value for the fopen() function to limit the time spent waiting for a response from the server.

$serverUrl = 'http://example.com';
$timeout = 5; // Set the timeout value in seconds

$context = stream_context_create(['http' => ['timeout' => $timeout]]);
$handle = @fopen($serverUrl, 'r', false, $context);

if ($handle) {
    // Server is reachable
    fclose($handle);
    echo 'Server is reachable.';
} else {
    // Server is unreachable
    echo 'Server is unreachable.';
}