What are the best practices for handling slow external server responses in PHP?
When dealing with slow external server responses in PHP, it's important to implement timeouts to prevent your script from hanging indefinitely. One way to handle this is by setting a timeout limit for the external server request using the `stream_context_create` function. This allows you to specify a maximum time for the request to complete before timing out.
// Set the timeout limit for the external server request
$context = stream_context_create(array(
'http' => array(
'timeout' => 10 // Timeout limit in seconds
)
));
// Make the external server request with the specified timeout
$response = file_get_contents('http://example.com/api', false, $context);
if ($response === false) {
// Handle timeout error
echo "Request timed out";
} else {
// Process the response from the external server
echo $response;
}