Anim8r
Anim8r

Reputation: 191

PHP Stop script file_get_contents() after 2 seconds

Okay so I have a PHP script that loads another page using file_get_contents().

The other page takes around 30 seconds to load (the type of script it is), and all I need is the file_get_contents() is to initiate this script.

The problem is, the file_get_contents() will stay loading for the whole 30 seconds. The only way to stop this is to close the tab (when closing the tab the script it calls still runs).

So, how can I get it so the file_get_contents(); closes after say 2 seconds?

Thanks in advance

Upvotes: 5

Views: 2862

Answers (3)

Álvaro González
Álvaro González

Reputation: 146540

In the manual page we can see that file_get_contents() accepts a third argument called $context were we are able to fine-tune our options. Following some links from there we reach HTTP context options where timeout appears to be our man:

timeout float

Read timeout in seconds, specified by a float (e.g. 10.5).

By default the default_socket_timeout setting is used.

So you can either provide a context or change default_socket_timeout (first option looks less prone to break other things).

Disclaimer: I haven't tested it.

Upvotes: 1

enenen
enenen

Reputation: 1967

Can't answer your question but I recommend using cURL instead file_get_contents.

Example:

function get_url_contents($url) {
    $crl = curl_init();

    curl_setopt($crl, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)');
    curl_setopt($crl, CURLOPT_URL, $url);
    curl_setopt($crl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($crl, CURLOPT_CONNECTTIMEOUT, 5);

    $ret = curl_exec($crl);
    curl_close($crl);
    return $ret;
}

Your issue may be from the timeout: default_socket_timeout

But this doesn't seem logically because 2 seconds is really very few and I can't explain myself why someone would change it to 2 seconds. The default is 60 seconds.

Upvotes: 3

monish
monish

Reputation: 182

may be you can use set_time_limit(2) before file_get_contents function call.

Upvotes: 0

Related Questions