Using timeouts with file_get_contents in PHP

If you are trying to use file_get_contents for fetching data from url’s, you might sometime need to define a timeout value. While it would seem as there is no obvious way, thanks to this comment on the manual page for file_get_contents, there is a pretty simple way.

// create the context
$arContext['http']['timeout'] = 3;
$context = stream_context_create($arContext);

// Fetch data
$url_data = file_get_contents('http://example.com', 0, $context);

There are other options too which can be seen here – http://www.php.net/manual/en/context.http.php

Advertisement