file_get_contents timeout

11,873

Solution 1

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);
?>

Solution 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);

Solution 3

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)

Share:
11,873
user1093588
Author by

user1093588

Updated on August 28, 2022

Comments

  • user1093588
    user1093588 almost 2 years

    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
      hakre about 12 years
      How can you say that it ignores that timeout setting?
    • joar
      joar about 12 years
      timeout was added in 5.2.1, check your PHP version.
    • user1093588
      user1093588 about 12 years
      I assigned a small value to the timeout and in spite of this file_get_contents returns the good result
  • user1093588
    user1093588 about 12 years
    I alreadey tried this ini_set('default_socket_timeout', 5); $xml = file_get_contents($hostName); But It doesn't work