I am using file_get_contents
, and I want to define a timeout. I tried to do it by creating a context like this:
$timeout = array('http' => array('timeout' => 6));
$context = stream_context_create($timeout);
$xml = file_get_contents($hostName,false,$context);
But It ignores this value.
As of PHP 5.2.1 you can specify timeout
context option and pass the context to file_get_contents()
ini_set('default_socket_timeout', 120);
Since I still cannot comment (and editing or flagging the question (as a duplicate(?)) probably is not quite appropriate in this case), let me add a follow-up question, and a comment as an answer:
I assigned a small value to the timeout and in spite of this file_get_contents returns the good result
Do you mean that even if you set a time-out of, say, 1 second, file_get_contents() takes more that that, and doesn't time out? Do you have any low level monitoring available to distinguish the time it takes to "connect", and "read" data?
(I realize this is an old question but, I ran into these 2 in my searches as I had the same question, and thought I should set up the link between them)
I suppose the default time out set is 60 sec. You can change that to what ever value you want to.
<?php
$ctx=stream_context_create(array('http'=>
array(
'timeout' => 30 // 30 sec
)
));
$conetnt = file_get_contents('http://example.com',false,$ctx);
var_dump($conetnt);
?>