Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set time limit on get_file_contents in PHP?

Tags:

php

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.

like image 731
Jagira Avatar asked Mar 13 '10 16:03

Jagira


1 Answers

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

?>
like image 180
Pekka Avatar answered Sep 19 '22 21:09

Pekka