How can a timeout of 3 seconds be implemented in a PHP script to prevent slow loading due to unreachable URLs?

When making requests to URLs in a PHP script, it's important to set a timeout to prevent slow loading due to unreachable URLs. This can be achieved by using the `stream_context_create` function to create a stream context with a timeout parameter. By setting the `timeout` parameter to 3 seconds, the script will wait for a maximum of 3 seconds before timing out if the URL is unreachable.

$url = "http://example.com";

$context = stream_context_create(array(
    'http' => array(
        'timeout' => 3
    )
));

$response = file_get_contents($url, false, $context);

if($response === false){
    echo "Error: Request timed out";
} else {
    echo $response;
}