tags:

views:

79

answers:

3

Hello,

At times the get_file_contents takes too long and that hangs the entire script. Is there any way of setting a time out limit on get_file_contents, without modifying the maximum execution time of the script?

Edit:

Its taking long because the file does not exist. I am getting "failed to open stream: HTTP request failed!" error. But it takes forever.

A: 

If it is taking a long time due to size.. I imagine you really don't want to be loading the entire contents into RAM.

You'd be better off processing line-by-line with fgets

Matt
I am fetching a json file, Its taking long because the file does not exist. But getting "failed to open stream: HTTP request failed!" error takes too long.
Jagira
+6  A: 

Seems to be possible in PHP > 5.2.1 by creating a context with the timeout option.

Slightly amended example from the manual page:

<?php

$opts = array('http' =>
    array(
        'method'  => 'GET',
        'timeout' => 120 
    )
);

$context  = stream_context_create($opts);

$result = file_get_contents('http://example.com/get.php', false, $context);

?>
Pekka
+1 : I love it when people suggest to use streams *(which are one of the great things of PHP that almost noone knows about ;-( )*
Pascal MARTIN
thanks... working like a charm :-)
Jagira
A: 

you count use ini_set and set "default_socket_timeout" before using file_get_contents and then restore the old value after it - if would affect some other parts of your code...

Laimoncijus