1

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.

hakre
  • 193,403
  • 52
  • 435
  • 836
user1093588
  • 31
  • 1
  • 1
  • 3

3 Answers3

3

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);
?>
HackerNews
  • 153
  • 1
  • 10
2

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);
Ibrahim Azhar Armar
  • 25,288
  • 35
  • 131
  • 207
  • I alreadey tried this ini_set('default_socket_timeout', 5); $xml = file_get_contents($hostName); But It doesn't work – user1093588 Apr 17 '12 at 10:30
2

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:

  • When you said:

    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?

  • Because as Fanis said in his answer to question "PHP file_get_contents ignoring timeout?", if you're using "file_get_contents()" (and not lower level socket functions), the time to "connect" to the remote server cannot be set by the available ini setting, or the context entry apparently. You only set the "read" time out by those.

(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)

Community
  • 1
  • 1
OzgurH
  • 443
  • 2
  • 13