What are some best practices for setting timeouts in PHP scripts that interact with external servers?

When interacting with external servers in PHP scripts, it is important to set timeouts to prevent the script from hanging indefinitely if the server is unresponsive. One common way to set timeouts is by using the `stream_context_set_params()` function to configure the timeout for stream operations. This allows you to specify the maximum amount of time the script should wait for a response from the server before timing out.

// Set timeout for stream operations
$context = stream_context_create([
    'http' => [
        'timeout' => 10 // Timeout in seconds
    ]
]);

// Make a request to an external server with the configured timeout
$response = file_get_contents('http://example.com/api', false, $context);

if ($response === false) {
    // Handle timeout or connection error
    echo "Request timed out or failed";
} else {
    // Process the response from the server
    echo $response;
}